Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Git current branch

The shell used in the following examples is bash, but the commands can be adapted for other shells.

reading it

Determine if working in a git repository

The goal here is to have a performant way to determine if we are in a git repo without printing anything.

git status --porcelain --untracked-files=no &>/dev/null && \
	echo 'in a git repo' || echo 'not in a git repo'

Print current branch if in git repo

Now we'll add the current branch.

git status --porcelain --untracked-files=no &>/dev/null && \
	git rev-parse --abbrev-ref HEAD

Print current repo and branch as two words

Add the local name of the repo.

git status --porcelain --untracked-files=no &>/dev/null && \
	echo -n "$(basename $(git rev-parse --show-toplevel)) " && \
	git rev-parse --abbrev-ref HEAD

using it

Depending your shell, these commands or variations of them could be used to add the current repo/branch to your command prompt or the title of your current terminal window.

Bash and zsh users can also use an existing solution included in the git repo: https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.