How to Create Branch From a Commit in Git
Stewart Nguyen
Feb 02, 2024
This article will demonstrate how to create a new branch from a commit.
To create a branch from an SHA commit, use the command git branch <new_branch> <commit_sha>
with the commit as the last argument.
You can also use a symbolic reference instead of sha
, for example, git branch <new_branch> HEAD~4
.
$ git log
commit 1e087f5309ae647d16a0e1469dfd12a7cd91e22d (HEAD -> feature/changes-to-file)
Author: Cuong Nguyen
Date: Sat Dec 18 22:01:00 2021 +0700
Make some change to file.txt
commit ab38737fe95f4959139b995b960a0173b4dd2c7e
Author: Cuong Nguyen
Date: Sat Dec 18 21:26:31 2021 +0700
Hotfix #1
$ git branch branch-from-hotfix-commit ab38737fe95f4959139b995b960a0173b4dd2c7e
$ git checkout branch-from-hotfix-commit
Switched to branch 'branch-from-hotfix-commit'
$ git log
$ git log
commit ab38737fe95f4959139b995b960a0173b4dd2c7e (HEAD -> branch-from-hotfix-commit)
Author: Cuong Nguyen
Date: Sat Dec 18 21:26:31 2021 +0700
Hotfix #1
To checkout the branch when it’s been creating, use git checkout -b <new_branch> <commit_sha>
.
Related Article - Git Branch
- How to Determine the Current Branch in Git
- Git Fork vs Branch
- Difference Between Forking and Branching on GitHub
- How to View Merged and Unmerged Branches in Git
- How to Show Remote Tracking Branches in Git
- How to Create an Empty Branch on GitHub