0
0
GitHow-ToBeginner · 3 min read

How to Create a Git Branch from a Specific Commit

Use git branch <branch-name> <commit-hash> to create a new branch from a specific commit. This command points the new branch to the chosen commit without changing your current branch.
📐

Syntax

The command to create a branch from a specific commit is:

  • git branch <branch-name> <commit-hash>: Creates a new branch named <branch-name> at the commit identified by <commit-hash>.
  • <branch-name>: The name you want to give your new branch.
  • <commit-hash>: The unique identifier of the commit where the branch will start.

This command does not switch your working directory to the new branch. To switch, use git checkout <branch-name> or git switch <branch-name>.

bash
git branch <branch-name> <commit-hash>
💻

Example

This example shows how to create a branch named feature-branch from a specific commit hash 1a2b3c4d and then switch to it.

bash
git branch feature-branch 1a2b3c4d
git switch feature-branch
Output
Switched to branch 'feature-branch'
⚠️

Common Pitfalls

Not switching to the new branch: After creating the branch, you remain on your current branch unless you switch manually.

Using incomplete commit hash: The commit hash must be unique enough to identify the commit. Using too few characters can cause errors.

Typo in branch name or commit hash: Mistakes in names cause errors or unexpected behavior.

bash
git branch feature-branch 1a2b3
# Might fail if '1a2b3' is ambiguous or too short

git switch feature-branch
# Switches to the new branch after creation
Output
error: ambiguous argument '1a2b3': unknown revision or path not in the working tree.
📊

Quick Reference

CommandDescription
git branch Create a new branch at the specified commit
git switch Switch to the new branch
git checkout Legacy way to switch branches
git log --onelineView commit hashes to find the right commit

Key Takeaways

Use 'git branch ' to create a branch from a specific commit.
You must switch to the new branch manually using 'git switch '.
Ensure the commit hash is unique and correctly typed to avoid errors.
Use 'git log --oneline' to find commit hashes easily.
Creating a branch from a commit does not change your current working branch automatically.