When you create a git repository, a branch named “master” is created, and becomes the active branch. It is the default development branch.
You can create more branches in the same repository. A branch in Git is simply a lightweight movable pointer to one of the commits.
Creating a git repository and creating a commit.
1 . Creating a branch
To create a new branch use command :
$ git branch new_branch
To check whether the branch is created or not using command :
$ git branch
To go to the branch use the command :
$ git checkout new_branch
The branch name with the asterisk(*) next to it indicates which branch you’re pointed to at that given time.
Lets create one more branch new_branch.1 using command :
$ git checkout -b new_branch.1
This command does two things at a time first it creates a new branch and then it also takes us to the same branch created.
Now look at the branches you have created .
$ git branch
If you switch back to the master branch and make some more commits, your new branch won’t see any of those changes until you merge those changes into your new branch.
2. Merging Branches
Create a file “file1” , add file to git and then commit in new_branch1
$ git checkout new_branch.1
$ touch file1
$ git add file1
$ git commit - m "this is file1 in branch new_branch1"
Now we will merge new_branch1 with master branch, but before merging you need to checkout from the branch and come to the master branch.
$ git checkout master
$ git merge new_branch.1
Using command git log, you can see new_branch.1 is merged into master branch, thats why file1 is included in master branch .
$ git log
3. Reverting Branches
The git revert command is undo operation that offers a safe method of undoing changes, instead of deleting commits in the commit history, a revert will create a new commit that inverses the changes specified.
If your current branch contains changes that you no longer want to release you can revert all or a portion of a project. Lets revert the changes we made in the last commit using commands :
$ git revert HEAD
$ git revert -m 1 0a5fcb4ffb14c65000d073a5786b508118d3d6f3
We specify the merge using the SHA1 hash of the merge commit,
-m followed by -1 indicates that we want to keep the parent side of the merge (the branch we are merging into).
Now check your git log.
4. Deleting Branches
To better understand deletion of branches, lets create some more branches:
$ git branch branch1
$ git branch branch2
$ git branch branch3
$ git branch branch4
Suppose if you are done with a branch and you don’t need it anymore you can delete the branch using following commands:
$ git branch -d branch1
$ git branch -d branch2 branch3 branch4 new_branch.1
You can also use
-D, which means
--delete --force, which deletes the branch “irrespective of its merged status.
$ git branch -D branch_name