This post will discuss how to create a branch from some previous commit in Git.
1. git-branch
To create a branch from some previous commit, you can use the git-branch command.
This creates a new branch, branchname
which whose head points to specified commit-id
. For example, the following creates a develop branch from the specified commit hash.
You can refer to a commit using its full SHA-1 hash or by providing the partial hash. The partial hash should contain the first few characters of the 40-character SHA-1 hash, and be at least four characters long and unambiguous.
You can also refer to a commit is via its ancestry:
The GIT manual specifies all ways to refer to any commit.
After creating the new branch, you will need to push the new branch to the remote repository. This can be done using git push
:
git branch develop 04c900c
# Push the new branch to the remote repository
git push --set-upstream origin develop
# Check out the new branch
git checkout develop
Here’s a live example demonstrating this:
2. git-checkout
Here, the idea is to check out the particular commit and then create a branch from that commit:
git checkout <commit-id>
# Create a new branch
git checkout -b <branchname>
We can simplify this to a single step:
git checkout -b <branchname> [<commit-id>]
After creating the new branch, you can push it to the remote repository.
git push --set-upstream origin <branchname>
3. git-reset
Alternatively, you can create a new branch from the current branch’s head and hard reset it to a specific commit. This can be easily done by git reset.
git checkout -b <branchname>
# Remove the commits made after <commit-id>
git reset --hard <commit-id>
# Push the new branch to the remote repository
git push --set-upstream origin <branchname>
Here’s a live example demonstrating this:
4. GitHub
Finally, GitHub provides a quick way to create a new branch from a specific commit. Following are the steps:
1. Go to your repository in GitHub and find the specific commit under the ‘x commits’ tab.
2. Click on the ‘Browse the repository at this point in the history’ link for that specific commit.
3. Click on the ‘Tree: sha-1 hash‘ drop-down, enter your branch name in the ‘Find or Create Branch’ input box and click on the create branch option.
4. That’s it. Your branch is created. Do a git fetch to pull it in your local.
That’s all about creating a branch from a previous commit in Git.