Git Branching


Git branching is the way by which we can split our code repository into different branches and it’s very useful when multiple developers work on the same code base.

How to list branches?

git branch  #show all local branches.
git branch -r  #show all remote branches.
git branch -a  #show all local and remote branches.
git show-branch  #show branches and their commits.

How to find out which is the current branch?

git branch  #* master

How to create a branch?

git branch branch_name  #reate a branch named name from “master”. The master can also be any {commit ID, branch name, tag name}.

Note: this does not switch you to the newly created branch.

How to switch to a branch (checkout a branch)?

Note: before you switch to a branch, best to commit your changes first.

git checkout branch_name  #update current dir's files to be the branch named branch_name's code. (technically: updating the index, working tree, and HEAD to reflect the specified branch.)

How to rename branch?

git branch -m old_name new_name  #rename branch.
git branch -M old_name new_name  #ename branch, even if there already exists a branch named new_name.

How to merge branch?

WARNING: you should commit before you merge, because, otherwise, when merge has conflicts it’s hard to revert to your uncommitted pre-merge state.
First, switch to the branch you want to merge to.

git checkout branch_name
git merge name  #merge a branch named name into the current branch (typically the “master”).

Note: merge won’t remove a branch. After you merge, you can remove a branch by git branch -d branch_name

How to remove/delete a branch?

git branch -d branch_name  #delete the branch. (the branch must be merged first)
git branch -D branch_name  #force delete the branch.

About the Author: Pankaj Bisht