I find there are two different times I want to get the current branch name: 1. When I’m at the command line, 2. Inside a Git alias function I’m writing. Interestingly, I find that my approach in these two situations are different.
Getting the Git Branch Name from the Command Line
At the command line, I can run
git branch --show-current
Note: This command was added to git show in version 2.22.0 released in June 2019. If you’re using an older version of Git, I would update (or keep reading for the legacy method).
Getting the Git Branch Name in an Alias Function
As mentioned above git branch --show-current
only works in Git 2.22.0
or newer and since our goal in a Git alias function is maximum compatibility I prefer to use this legacy method.
git rev-parse --abbrev-ref HEAD
This command returns the same information as git branch --show-current
but it is compatible with older versions of Git.
Copy Git Branch Name to Clipboard
One trick I often use on MacOS is to copy the current branch name to my clipboard with
git branch --show-current | pbcopy
Leave a Reply