To create a Git branch starting from a previous commit, follow these steps:
1. Find the Commit Hash
Use git log
to locate the commit you want to branch from:
git log --oneline # Shows abbreviated commit hashes and messages
# Example output:
# a1b2c3d (HEAD -> main) Add feature X
# d4e5f6a Fix bug
# 7g8h9i0 Initial commit
2. Create a New Branch from the Commit
Option A: Create and Switch to the Branch
git checkout -b <new-branch-name> <commit-hash>
# Example:
git checkout -b new-feature d4e5f6a
Shortcut with relative references (e.g., HEAD~2
for 2 commits back):
git checkout -b new-feature HEAD~3 # Branches from 3 commits ago
Option B: Create the Branch Without Switching
git branch <new-branch-name> <commit-hash>
# Example:
git branch hotfix a1b2c3d
Then switch to it later:
git checkout hotfix
# Or (Git 2.23+):
git switch hotfix
3. Verify the New Branch
git log --oneline # Confirm the branch starts at the correct commit
4. Push the Branch to Remote (Optional)
git push -u origin <new-branch-name>
Key Notes
- Commit Hash: Use the full or abbreviated hash (e.g.,
d4e5f6a
). - Relative Refs:
HEAD~n
refers to the nth ancestor of the current commit. - Detached HEAD: If you check out a commit directly (without
-b
), you’ll enter a detached HEAD state. Create a branch to retain changes.
Example Workflow
- List recent commits:
git log --oneline
# Output:
# d4e5f6a (main) Update README
# a1b2c3d Add login feature
# 7g8h9i0 Initial commit
- Branch from
a1b2c3d
:
git checkout -b login-fixes a1b2c3d
- Push to remote:
git push -u origin login-fixes
Why This Works
- Git branches are just pointers to commits. Creating a branch from an older commit lets you develop independently from that point.
- Useful for:
- Fixing bugs in older releases.
- Experimenting without affecting the main branch.
- Isolating features from historical states.