To create a new Git branch from an old commit, follow these steps:
- Determine the commit hash:
First, identify the commit hash of the specific commit you want to use as the starting point for the new branch. You can do this by running git log to view the commit history.
Example:
shgit log --oneline
- Create a new branch:
Then, use the following command to create a new branch, specifying the commit hash found in step 1 as the starting point.
shgit checkout -b new-branch-name commit-hash
Here, new-branch-name is the name of the branch you want to create, and commit-hash is the hash of the commit you want the new branch to start from.
For example, if you want to create a new branch named feature-x starting from the commit with hash 9fceb02, you would use the following command:
shgit checkout -b feature-x 9fceb02
This creates the feature-x branch starting from the specified commit. You can then continue working on it, making commits, without affecting the original branch.
- Push the new branch (optional):
If you want to push this newly created branch to the remote repository, use the following command:
shgit push -u origin new-branch-name
This ensures that the new branch is recorded both locally and remotely. The -u option associates the local branch with the remote branch, so you can omit specifying the branch name in subsequent pushes (git push) or pulls (git pull).
For a concrete example, suppose you are working in a repository named legacy-project. You found an old commit with hash d792fb82 that fixes an important bug. You want to create a new branch based on this commit for experimental changes. You execute the following command:
shgit checkout -b experimental-fix d792fb82
After creating the experimental-fix branch, you can make modifications and experiments on it without interfering with the main branch main or other branches. Once you complete the experiments, you can decide whether to merge these changes back into the main branch or other relevant branches. If you are satisfied, you can also push this experimental branch to the remote repository:
shgit push -u origin experimental-fix
This allows other team members to review or further develop your experimental branch.