Git Branching Tutorial

, , …,

This page is a basic & practical tutorial on git branching.

I assume you never branched before, but you are familar with git basics, such as {status, add, commit, push, pull}. If not, see: git Tutorial.

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 branche?

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 new name → rename branch.

git branch -M old name new name → rename 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 uncommited pre-merge state.

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

thanks to Nick Alcock for help.

blog comments powered by Disqus