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
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