In this short guide, I will show you how to create a git branch from a particular commit.
Related Article : Git local and remote branches
Branching is an important concept in Git that allows you to change your repository without impacting the existing code base. Think of a branch as an isolated container with some existing data where any changes you make will sit inside that container and will not be able to interact with other branches unless we merge it.
By default, git creates a branch called master when you initialize a repository and create your first commit.
$ mkdir /tmp/nixzie-git-branch
$ cd /tmp/nixzie-git-branch
$ git init
Initialized empty Git repository in /tmp/nixzie-git-branch/.git
You can run the git branch command and you will not be able to see any branches. This is because git will create the default master branch only when you create the first commit.
$ echo "nixzie - first commit for testing" > nixzie-sample.txt
$ git add .
$ git commit -m "nixzie-sample.txt first commit"
Now run the git branch command and you can see the default branch.
$ git branch
main
$ git branch -v
* main 2b6a2ce nixzie-sample.txt first commit
In my case, the default branch name is set to main instead of master. In your case, it can be master, main or any other name depending on how you configured it.
RELATED ARTICLE – How To Set Default Branch Name In Git & Github
Let’s create two more commits in the main branch.
$ echo "nixzie - second commit for testing" > nixzie-sample.txt
$ git add .
$ git commit -m "nixzie-sample.txt second commit"
$ echo "nixzie - third commit for testing" > nixzie-sample.txt
$ git add .
$ git commit -m "nixzie-sample.txt third commit"
Currently, my main branch has three commits. You can create a new branch by running any of the following commands.
$ git checkout -b <BRANCH-NAME>
$ git switch -c <BRANCH-NAME>
Here I am creating a branch called feature/TICKET123. The -c flag will automatically switch to the newly created branch.
$ git switch -c feature/TICKET123
Switched to a new branch 'feature/TICKET123'
Now this branch is created from the tip of the main branch.
$ git log --oneline --graph
* d342a05 (HEAD -> feature/TICKET123, main) nixzie-sample.txt third commit
* 15e70b2 nixzie-sample.txt second commit
* 2b6a2ce nixzie-sample.txt first commit
But let’s say we want to create the branch from the HEAD~2 commit which is one commit below the HEAD. The command will be the same but you have to pass the commit SHA as an additional argument.
$ git switch -c feature/TICKET234 15e70b2
The branch feature/TICKET234 is not created from the 15e70b2 commit instead of the tip of the branch.
$ git log --oneline --graph
15e70b2 (HEAD -> feature/TICKET234) nixzie-sample.txt second commit
2b6a2ce nixzie-sample.txt first commit
Wrap Up
In this short guide, we have seen how to create a git branch from a particular commit in the git history.