Posted: . At: 10:43 AM. This was 3 years ago. Post ID: 14784
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


How to have a nice bash shell prompt that will print the current git branch on the prompt.


This interesting bash function will get the git branch of the current working directory and then print it in the shell prompt. This could be very useful for a programmer.

git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
 
PS1='┌──[\u@\h]─[\w]\n└──╼ $(git_branch) ╼ \$ '

This looks just like a normal shell prompt.

┌──[jason@jason-desktop][~]
└──╼  ╼ $ cd Documents/xray-16/

But when I cd into a directory containing code I got from Github, it shows that it is using a certain Git branch.

┌──[jason@jason-desktop][~/Documents/xray-16]
└──╼ (xd_dev) ╼ $

This indeed would be very useful for someone who uses Git on a regular basis, this would inform you which branch you are pushing to and hopefully avoid embarrassing mistakes.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.