How do I get the current branch name in Git?

To get the current branch name in Git, use one of the following commands:

1. git branch --show-current (Recommended for Git 2.22+)

git branch --show-current
  • Output: Directly prints the current branch name (e.g., main).
  • Pros: Simple and explicit. Added in Git 2.22.0 (2019).

2. git rev-parse --abbrev-ref HEAD (Universal)

git rev-parse --abbrev-ref HEAD
  • Output: Returns the short name of the current branch (e.g., main).
  • Works in scripts: Safe for automation (avoids parsing text).

3. git symbolic-ref --short HEAD

git symbolic-ref --short HEAD
  • Output: Same as above (branch name like main).
  • Note: Fails in “detached HEAD” state (e.g., when checking out a commit instead of a branch).

4. Parse git branch Output

git branch | grep '^*' | cut -d ' ' -f2-
  • How it works: Lists branches, filters the line starting with *, and extracts the branch name.
  • Cons: Fragile for scripting (relies on output formatting).

Example Output

$ git branch --show-current
main

Handling Detached HEAD State

If you’re in a “detached HEAD” state (not on any branch), the commands above will return HEAD instead of a branch name. To check if you’re on a branch:

if git symbolic-ref --short HEAD >/dev/null 2>&1; then
  echo "On branch: $(git branch --show-current)"
else
  echo "Detached HEAD state"
fi

Use in Scripts

Assign the branch name to a variable:

current_branch=$(git branch --show-current)
# or
current_branch=$(git rev-parse --abbrev-ref HEAD)

Summary

CommandBest ForDetached HEAD Handling
git branch --show-currentModern GitReturns HEAD
git rev-parse --abbrev-ref HEADCross-versionReturns HEAD
git symbolic-ref --short HEADDirect queryFails (error code 1)

Use git branch --show-current if your Git version supports it (check with git --version). For compatibility, git rev-parse is the safest bet!

Leave a Reply

Your email address will not be published. Required fields are marked *