brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: git branch --show-current prints only the name of your branch

Git
~/tips/tip-git-branch-show-current

git branch --show-current

Prints the name of the current branch and nothing else, which is handy in scripts and prompts.

To get the branch name in a script, people parse the output of git branch and look for the asterisk. There is an option that prints just the name.

git branch --show-current

That is the whole command. It prints the current branch name, for example main, and nothing else, so you can use it directly.

git push origin "$(git branch --show-current)"

It is also easy to use in a shell prompt, a backup script or a commit hook that treats main differently from feature branches.

In a detached HEAD state, for example after checking out a tag or an old commit, the command prints nothing. That is useful because an empty result tells your script there is no branch, instead of printing a strange (HEAD detached at ...) line that you have to filter out. In a script you can test for it with [ -z "$(git branch --show-current)" ].

The caveat is the version: the option arrived in Git 2.22, so older systems fail with an unknown option error. On those you can fall back to git rev-parse --abbrev-ref HEAD, though that prints HEAD when detached.

Further reading: git-branch documentation

More Git tips git show-branch main feature git log --stat -5 git merge --no-ff feature -m "Merge feature" git merge --squash feature git merge --abort All Git tips (144) All topics

Link