Last Updated on January 30, 2021 by sandeeppote

Branches are used to isolate working folder. The HEAD always point to the current branch and can be checked as follows-

 cat .git/HEAD

This shall give the reference where the HEAD point to.

Before creating a branch you may check the if its already created by-

git branch

This shall display the list of branch in current repository.

To create a new branch-

 git branch branch_name

Use basic letters and punctuation for branch name. Although the branch is created it is not yet checkout to use. To switch the branch-

 git checkout branch_name

You may also use following to create and switch to the new branch-

 git checkout -b "branch_name"


Switching between branches

If you want to switch between the branches that are already created-

git checkout branch_name

If there are staged changes but changes not committed you wont be able to switch between branch as git gives a warning that the changes done in current branch might be overwritten-

Comparing branches
If you want compare the difference between the branches-

git diff master..branch_name

master and branch_name are branches been compared here.
.. is a range operator.

“Changed file content” text in the fileafterrenaming.txt is the change between branches

If you want to see the differences with colored text-

 git diff --color-words master..branch_name


Rename branch

You might want to rename branch to match to the changes it has or if you are resolving and defect to identify branch with the ticket number or name. To rename branch-

 git branch -m branch_you_wan_to_rename newname

Deleting branch
If you are up to deleting a branch switch to master branch as you are not able to delete the branch if its been checked out and hit below command-

 git branch -d branch_to_delete

If there are changes that are not merged between branches git wont allow to delete the branch and shall provide following warning- To see the difference use

git diff


 git branch -d new-branch


As it suggests if you want to really delete use -D to permanently delete the branch losing the changes-

git branch -D new-branch


Creating branch from remote-

If you want to checkout and create a local branch from remote-

 git checkout -b local_branch_name remote_branch_name

Here all changes from remote_branch_name will be available in local machine with the branch name local_branch_name