Skip to content

Instantly share code, notes, and snippets.

@putnamhill
Last active March 16, 2019 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save putnamhill/9742c0030a6f4954fa93954fe95ba457 to your computer and use it in GitHub Desktop.
Save putnamhill/9742c0030a6f4954fa93954fe95ba457 to your computer and use it in GitHub Desktop.

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