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.
git-branch-2

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"

git-branch-1

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-
gitlog-oneline

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.

git-branch-3
“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

git-branch-4

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 master..new-branch

git-branch-6

 git branch -d new-branch

git-branch-7

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

git branch -D new-branch

git-branch-8

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