DEV Community

Rei Allen Ramos
Rei Allen Ramos

Posted on

3

Display current git branch in bash shell prompt

A pet peeve according to Google is something that a particular person finds especially annoying. A pet peeve according to me is when I need to type git status or git branch to double check I'm not accidentally mucking up the remote master.

You've added, committed, and now you're ready to push. Then you hear a voice from the back of your head nagging you to check if you're on the correct branch:

rapramos@rapdr_ramos:~/Documents/projects/my_awesome_project$ git branch
  awesome_branch
* master

Phew, dodged a bullet. Normally your remote master should be protected from accidental pushes but better safe than sorry.

Display your git branch in your command line

Fire up your editor and open /home/your_username/.bashrc. You should be able to find this setting:

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

Above the block, add:

show_git_branch() {
 git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}

Then call the function via $(show_git_branch) and insert it right before the last \$ for both cases. The final code should look like:

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$(show_git_branch)\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(show_git_branch)\$ '
fi
unset color_prompt force_color_prompt

Save, exit then run source ~/.bashrc to apply your changes. If everything was done correctly, congratulations because now you'll know what branch you're on all the time:

rapramos@rapdr_ramos:~/Documents/projects/my_awesome_project(master)$

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Instrument, monitor, fix: a hands-on debugging session

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️