Introduction to Git Branch

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?

Type git branch. The current branch is indicated by a asterisk *.


How to create a branch?

git branch name master → create 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 newName→ rename branch.

git branch -M old_name newName → rename branch, even if there already exists a branch named newName.

How to merge branch?

WARNING: you should commit before you merge, because, otherwise, when merge has conflicts it's hard to revert to your uncommited pre-merge state.

First, switch to the branch you wan to merge to. For example, 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.