How to Create a GIT Branch from a Commit?

How to Create a GIT Branch from a Commit?

Usually, a branch is created from another branch which is the latest HEAD commit of the branch. But what if you want to create a branch from a previous commit HEAD?

GIT branch can be created with a commit hash using the ‘git checkout’ command with ‘-b’ option and then pass a new branch name with the commit SHA.

$ git checkout -b <new-branch> <commit-sha>

Or, you can also use the 'git branch' command to create the branch without switching to the new branch.

$ git branch <new-branch> <commit-sha>

 

Here are the detailed steps to create a GIT branch from a commit hash with the git checkout command:

1. Find commit SHA with git log

The first step is to find the commit SHA from which you want to create the branch.

Use ‘git log’ command with ‘--online’ and ‘--graph’ options to get the commit SHA.

$ git log --oneline --graph

* 39710b8 (HEAD -> feature-2) Feature 2 added.
* ecddf76 Feature 1 added.
* 34cd5ff (new-branch, develop) Test commit.

Now you can see 3 commits in the git history.

2. Create new branch from commit SHA

Now let's assume you want to create a branch from the second commit with commit hash value 'ecddf76'.

$ git checkout -b feature-102 ecddf76

3. Confirm new branch head

Use 'git log' command again to make sure that the new branch is created from the correct commit SHA

$ git log --oneline --graph

* ecddf76 (HEAD -> feature-104) Feature 1 added.
* 34cd5ff (new-branch, develop) Test commit.

 

Now you have successfully created a new branch from a commit in the commit history.

Further reading: https://www.atlassian.com/git/tutorials/using-branches/git-checkout

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
6 + 5 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.