How do you create a new branch based on a specific commit?
Posted by OliviaWm
Last Updated: June 27, 2024
To create a new branch based on a specific commit in Git, you can use the git checkout or git switch command followed by -b to create the new branch, or you can use the git branch command explicitly. Here are the steps for each method:
Method 1: Using git checkout
1. Identify the Commit Hash: First, you need the hash of the commit you want to base the new branch on. You can find this hash by using git log. 2. Create and Checkout the New Branch: Once you have the commit hash, you can create and switch to the new branch using:
git checkout -b <new-branch-name> <commit-hash>
Replace <new-branch-name> with your desired branch name and <commit-hash> with the actual hash of the commit.
Method 2: Using git switch
1. Similar to above, first, get the commit hash using git log. 2. You can create and switch to the new branch with:
git switch -b <new-branch-name> <commit-hash>
Method 3: Using git branch and then switching
1. Again, start by getting the commit hash. 2. Create the new branch without switching:
git branch <new-branch-name> <commit-hash>
3. Then, switch to the new branch:
git checkout <new-branch-name>
or
git switch <new-branch-name>
Example
Assuming you want to create a branch named feature-branch based on the commit with the hash abc1234, you would do:
git checkout -b feature-branch abc1234
or using git switch:
git switch -b feature-branch abc1234
After creating the new branch, you are now located on feature-branch, starting from the specified commit.