0

I'm writing a prepare-commit-msg hook which appends the branch name to the commit msg. I m using this line to get the branch name

  local current_branch=$(git rev-parse --abbrev-ref HEAD)

The problem is that if no prior commit exists (when the repo was just initizalised) the command fails with the following error message

git rev-parse --abbrev-ref HEAD
HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.

Is there some better way to get at the branch name, or to suppress the warning / error?

helpermethod
  • 59,493
  • 71
  • 188
  • 276

2 Answers2

1
git symbolic-ref --short HEAD

See https://git-scm.com/docs/git-symbolic-ref

phd
  • 82,685
  • 13
  • 120
  • 165
0

This is such a rare rare case, it's barely worth worrying about surely. You could just add a default, and suppress the error

$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "default branch")
Mort
  • 3,379
  • 1
  • 25
  • 40