Show the Git branch in your terminal prompt

This is a cool hack to have your current git branch show up in your terminal prompt. It ends up looking like this:

user@box:~/dev/project:[my-dev-branch]$

If you're not in a git repository the [my-dev-branch] bit won't be there and it'll just be your regular prompt.

All you have to do is add the following to the bottom of your ~/.bashrc file:

function git-branch-prompt {
    branch=$(git branch 2>/dev/null | grep '^*' | colrm 1 2)
    if [ $branch ]; then printf " [%s]" $branch; fi
}
OPS1=$PS1
PS1=`echo ${OPS1:0:-3}'$(git-branch-prompt)\$ '`

Enjoy!

Hosted Gitea is a fully managed Gitea hosting service. If you're looking for a private alternative to GitHub or Gitlab check out our service.

Get your Gitea server