Instantly share code, notes, and snippets.

Embed
What would you like to do?
Display git branch in bash prompt
# If you work with git, you've probably had that nagging sensation of not knowing what branch you are on. Worry no longer!
export PS1="\\w:\$(git branch 2>/dev/null | grep '^*' | colrm 1 2)\$ "
# This will change your prompt to display not only your working directory but also your current git branch, if you have one. Pretty nifty!
# ~/code/web:beta_directory$ git checkout master
# Switched to branch "master"
# ~/code/web:master$ git checkout beta_directory
# Switched to branch "beta_directory"
# ~/code/web:beta_directory$
@dregad

This comment has been minimized.

dregad commented Nov 19, 2011

Why not simply use the __git_ps1 function ?

export PS1="\\w\$(__git_ps1 '(%s)') \$ "
@bjlbernal

This comment has been minimized.

bjlbernal commented May 24, 2013

__git_ps1 didn't work for me on my MacBook Pro.

-bash: __git_ps1: command not found

Resorted back to original post.

@keegan2149

This comment has been minimized.

keegan2149 commented Aug 19, 2013

Added the hostname

export PS1="\h\w:$(git branch 2>/dev/null | grep '^*' | colrm 1 2)$ "

@wayneseymour

This comment has been minimized.

wayneseymour commented Jan 30, 2014

Thanks man.
So far I'm at:

export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\] \[\033[33;1m\]\w\[\033[m\] (\$(git branch 2>/dev/null | grep '^*' | colrm 1 2)) \$ "
# gives me:
wayne  ~/dev/lrn (master) $ # my name in green, curr dir in yellow, and branch in green

Still a WIP.

:)

@dontfeedthecode

This comment has been minimized.

dontfeedthecode commented Jun 19, 2014

Try

export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\] \[\033[33;1m\]\w\[\033[m\] (\$(git branch 2>/dev/null | grep '^*' | colrm 1 2)) \$  \n| => "
export PS2="| => "

Depending what directory you're in the line gets a bit long, this starts the actual in put on the line below.

@onel0p3z

This comment has been minimized.

onel0p3z commented Jul 7, 2014

have you tried this ??

@navyad

This comment has been minimized.

navyad commented Aug 7, 2014

how to color the branch name ?

@vankasteelj

This comment has been minimized.

vankasteelj commented Mar 7, 2016

I'll leave this here:

PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \[\033[0;36m\]\h \w\[\033[0;32m\]$(__git_ps1)\n\[\033[0;32m\]└─\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\] ▶\[\033[0m\] '

capture_du_2016-03-07_19-13-07

@LeoFNaN

This comment has been minimized.

LeoFNaN commented Aug 26, 2016

Now that's a nice one @vankasteelj...(__git_ps1) doesn't work in my terminal on xubuntu so I substituted it with this gists original display method and removed the chevron symbol (personal preference)

PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \w\[\033[0;32m\]\n$(git branch 2>/dev/null | grep "^*" | colrm 1 2)\[\033[0;32m\]└─\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\]\[\033[0m\] '

@husnulhamidiah

This comment has been minimized.

husnulhamidiah commented Aug 28, 2016

How to change (master) to [master]

@jhit

This comment has been minimized.

jhit commented Sep 10, 2016

if __git_ps1 is not working take a look here: https://fedoraproject.org/wiki/Git_quick_reference
I needed to add source /usr/share/git-core/contrib/completion/git-prompt.sh to my ~/.bashrc to get it work.

@MrAaronOlsen

This comment has been minimized.

MrAaronOlsen commented Jun 1, 2017

I like this! __git_ps1 seems to force () around my branch and adds a space in front of it. Your option allows me to not have that which looks cleaner to me. If clutter in the ps1 string isn't desirable then folks always have the option of putting it in a bash function.

git_branch() {
  git branch 2>/dev/null | grep '^*' | colrm 1 2
}

export PS1="\$(git_branch)"

Gone are the days of working on master by accident... Thanks again!

@javieitez

This comment has been minimized.

javieitez commented Jun 28, 2017

The problem with PS1="\$(git_branch)"' is that it displays the empty parenthesis () when the current dir is not a git one. I've tweaked it like this to get rid of them.

gb() {
        echo -n '(' && git branch 2>/dev/null | grep '^*' | colrm 1 2 | tr -d '\n' && echo  -n ')'
}
git_branch() {
        gb | sed 's/()//'
}

It needs two functions because if we pipe everything into one line, the last sed command that strips the () doesn't receive the right input (notice the &&).

@giannidk

This comment has been minimized.

giannidk commented Jul 8, 2017

I made a small modification to @vankasteelj version, with square brackets around the branch name:

PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \w\[\033[0;32m\] - [$(git branch 2>/dev/null | grep "^*" | colrm 1 2)\[\033[0;32m\]]\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\]\[\033[0m\] '

screen shot 2017-07-08 at 16 51 57

@ghost

This comment has been minimized.

ghost commented Jul 15, 2017

Yet another variant, with a couple of nice features. First, I use PROMPT_COMMAND instead of PS1 to get coloured info, second I use GIT_PS1_SHOWDIRTYSTATE=1, GIT_PS1_SHOWCOLORHINTS=1,GIT_PS1_SHOWUNTRACKEDFILES=1 to turn on all the features.

Also, with long prompt strings, you almost certainly want a newline in there near the end, so that there is plenty of space on each line.

So putting it all together:

export GIT_PS1_SHOWDIRTYSTATE=1
export GIT_PS1_SHOWCOLORHINTS=1
export GIT_PS1_SHOWUNTRACKEDFILES=1

export PROMPT_COMMAND=' __git_ps1 "\n[\e[33m][[\e[m]\A [\e[31m]\u[\e[m]@[\e[32m]\h [\e[34;01m]\l[\e[m] [\e[36m]\w[\e[m]" "[\e[33m]][\e[m]\n$ "'

which gives this sort of thing:

bash_git

@skimpa

This comment has been minimized.

skimpa commented Sep 20, 2017

thanks guys ...helped me get what i was looking for
gitpic

@megadr01d

This comment has been minimized.

megadr01d commented Sep 24, 2017

With brew install git:

source /usr/local/etc/bash_completion.d/git-prompt.sh
export PS1="\w\$(__git_ps1 '[%s]') $ "
@dagolinuxoid

This comment has been minimized.

dagolinuxoid commented Oct 5, 2017

@gordboy somehow I've got a LOT of additional redundant empty brackets using your set up | definitely I messed up on something :)
threre is my old .bashrc

### Add Git Status to bash prompt
parse_git_branch() {
     git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w\[\033[33m\]\$(parse_git_branch)\[\033[00m\]\n$ "

#### Change terminal title
PROMPT_COMMAND='echo -ne "\033]0;${PWD}\007"'

@samsoul16

This comment has been minimized.

samsoul16 commented Oct 13, 2017

@skimpa can you share your PS1 i liked the style that you have created and i want to use the same one.

@stucash

This comment has been minimized.

stucash commented Oct 18, 2017

@vankasteelj a year later still working like a charm on ubuntu 16.04, nicely done. thanks a lot

@fritzmatias

This comment has been minimized.

fritzmatias commented Nov 9, 2017

@iuliaL

This comment has been minimized.

iuliaL commented Jan 9, 2018

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

export PS1="\u@\[\033[32m\]\w\[\033[33m\]\$(git_branch)\[\033[00m\]\$ " 

optional parenthesis 💯

@niketpathak

This comment has been minimized.

niketpathak commented Jan 10, 2018

Another version along with the status of your current branch (dirty, stashed content, etc)
http://digitalfortress.tech/tutorial/setting-up-git-prompt-step-by-step/

@tzago

This comment has been minimized.

tzago commented Feb 8, 2018

Using vankasteelj version on debian strech and working as expected. Thank you guys!!!

@zenglian

This comment has been minimized.

zenglian commented Mar 9, 2018

Use a different color for the branch name?

@prophetnoise

This comment has been minimized.

prophetnoise commented Mar 16, 2018

As an alternative, i wanted my Terminal (mac) window's title to display the branch as i navigated instead of the prompt. Added the https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh file to my home directory as .git-prompt-sh

Added to my .bash_profile:

if [ -f ~/.git-prompt.sh ]; then
  source ~/.git-prompt.sh
fi

function cd () { builtin cd "$@" && printf "\033]0;$(__git_ps1 '%s')\007"; }
function checkout () { git checkout "$@" && printf "\033]0;$(__git_ps1 '%s')\007"; }
@khadijanazih

This comment has been minimized.

khadijanazih commented Mar 22, 2018

I used this:

export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\] \[\033[33;1m\]\w\[\033[m\] (\$(git branch 2>/dev/null | grep '^*' | colrm 1 2)) \$ "

it worked fine for me but I want to shorten the path to this : [user]@[current directory](current branch) with the colors of course.

How can I do it !!

@jeroendesloovere

This comment has been minimized.

jeroendesloovere commented Apr 26, 2018

@khadijanazih, use the following (from @giannidk and @vankasteelj):
PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \w\[\033[0;32m\] - [$(git branch 2>/dev/null | grep "^*" | colrm 1 2)\[\033[0;32m\]]\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\]\[\033[0m\] '

@rioj7

This comment has been minimized.

rioj7 commented May 2, 2018

@vankasteelj some color commands are not needed, removing gives the following prompt

PS1='\[\033[32m\]\u \[\033[36m\]@ \h \w\[\033[32m\]$(__git_ps1)\n└─ \$ ▶\[\033[0m\] '
@niketpathak

This comment has been minimized.

niketpathak commented May 25, 2018

You could even color the git prompt depending on the state of your repository. For example, "Red" if there are any changes in the repo, "Green" otherwise, etc...
Setup up Git prompt

@ishitvagoel

This comment has been minimized.

ishitvagoel commented Jul 26, 2018

We can now even copy paste emojis in the PS1 prompt string.
Added three emojis to the version specified by @vankasteelj

Screenshot:
https://screenshots.firefox.com/pOjRfrgZMXbnaUHP/null

@Iqlaas

This comment has been minimized.

Iqlaas commented Jul 30, 2018

screen shot 2018-07-30 at 3 34 36 pm
Hi All. How do I do it like above ? Dont mind the emoji, I know its representing the user's machine name.

It shows only the repository name, (not including its path if it were to go into a subfolder), git:(current branch), and some x.
Tried to search online but could not find any.

So in short (user)@(repo name only)git:(current branch)(space)x

Sorry I forgot I am using zsh.
Please help! Thank you!

@bl4ck4ndbr0wn

This comment has been minimized.

bl4ck4ndbr0wn commented Aug 18, 2018

parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^]/d' -e 's/ (.*)/ (\1)/'
}
export PS1="\u@\h [\033[32m]\w[\033[33m]$(parse_git_branch)[\033[00m] $ "

image

@Sibasish19

This comment has been minimized.

Sibasish19 commented Aug 26, 2018

@vankasteelj working on Debian 16.04 and it's working like a charm. Thank you. However this change is not permanent in my case, I have to reload bash_profile every time I open a new terminal. Any fix for that?
PS: this thread is gold!

@hansfn

This comment has been minimized.

hansfn commented Sep 7, 2018

Why aren't you using git symbolic-ref HEAD --short instead of git branch and grepping for stars?

@shivakumargn

This comment has been minimized.

shivakumargn commented Sep 14, 2018

@hansfn, that is indeed better than git branch. 'git branch` can be visibly slow to show the prompt on large repos with lots of branches.

@nnungest

This comment has been minimized.

nnungest commented Sep 18, 2018

@Sibasish19 you can add this to your ~/.bashrc instead if you'd like.

@hansfn

This comment has been minimized.

hansfn commented Sep 20, 2018

vankasteelj wrote on Mar 7, 2016

I'll leave this here:

PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \[\033[0;36m\]\h \w\[\033[0;32m\]$(__git_ps1)\n\[\033[0;32m\]└─\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\] ▶\[\033[0m\] '

capture_du_2016-03-07_19-13-07

Isn't there just too much going on? Even more unreadable than normal ;-) The following should be the same.

PS1='\[\033[0;32m\]\u\[\033[0;36m\] @ \[\033[0;36m\]\h \w\[\033[0;32m\]$(__git_ps1)\n\[\033[0;32m\]└─\[\033[0;32m\] \$\[\033[0;32m\] ▶\[\033[0m\] '

If you in addition remember that a color sticks until is changed or reset, we get:

PS1='\[\033[0;32m\]\u\[\033[0;36m\] @ \h \w\[\033[0;32m\]$(__git_ps1)\n└─ ▶\[\033[0m\] '

I'm just mentioning this in case people copies vankasteelj code and tries to understand it ...

PS! Reading Bash Prompt HOWTO: Colors and https://bash.cyberciti.biz/guide/Changing_bash_prompt is very useful.

@nemopohle

This comment has been minimized.

nemopohle commented Sep 27, 2018

All I wanted is a simple, colored one-line prompt. @vankasteelj provided a nice one, I just extended it by not displaying brackets when outside a repo:

PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \w\[\033[0;32m\]$(if git rev-parse --git-dir > /dev/null 2>&1; then echo " - ["; fi)$(git branch 2>/dev/null | grep "^*" | colrm 1 2)\[\033[0;32m\]$(if git rev-parse --git-dir > /dev/null 2>&1; then echo "]"; fi)\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\]\[\033[0m\] '

@weilinzung

This comment has been minimized.

weilinzung commented Sep 28, 2018

Is possible to add the current branch name on all the timestamp lines? Something like this:

FROM:

[18:37:39] Starting 'build-js'...
[18:37:49] finished 'build-js'...

TO:

[18:37:39 - **current-branch-name** ] Starting 'build-js'...
[18:37:49 - **current-branch-name** ] finished 'build-js'...

Thanks.

@cornensue

This comment has been minimized.

cornensue commented Sep 29, 2018

I like this one, thanks:

PS1='[\033[0;32m][\033[0m\033[0;32m]\u[\033[0;36m] @ [\033[0;36m]\h \w[\033[0;32m]$(__git_ps1)\n[\033[0;32m]└─[\033[0m\033[0;32m] $[\033[0m\033[0;32m] ▶[\033[0m] '

@jedmao

This comment has been minimized.

jedmao commented Oct 4, 2018

I like this short directory formatting:

screen shot 2018-10-04 at 5 05 23 pm copy

function shortwd() {
    num_dirs=3
    pwd_symbol="..."
    newPWD="${PWD/#$HOME/~}"
    if [ $(echo -n $newPWD | awk -F '/' '{print NF}') -gt $num_dirs ]; then
        newPWD=$(echo -n $newPWD | awk -F '/' '{print $1 "/.../" $(NF-1) "/" $(NF)}')
    fi 
    echo -n $newPWD
}

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

PS1='\n\e[38;5;211m$(shortwd)\e[38;5;48m $(git_branch)\e[0m$'
export PS1
@kamok

This comment has been minimized.

kamok commented Oct 12, 2018

I like this better:

Git Aware Prompt - https://github.com/jimeh/git-aware-prompt

export GITAWAREPROMPT=~/.bash/git-aware-prompt
source "${GITAWAREPROMPT}/main.sh"

PS1

export PS1="[$txtblu]\w [$txtgrn]$git_branch[$txtred]$git_dirty[$txtrst]$ "

I use iTerm2, so I can go into the preferences and change $txtblu with a nice UI color picker.

image

@tdwebste

This comment has been minimized.

tdwebste commented Oct 23, 2018

pt_user_co() {
    if [ "$(id -u)" == "0" ]; then
        echo -en "\033[1;31m"
    else
        echo -en "\033[1;32m"
    fi
}

pt_host_co() {
    if [[ ${SSH_CLIENT} ]] || [[ ${SSH2_CLIENT} ]]; then 
        echo -en "\033[1;35m"
    else
        echo -en "\033[1;34m"
    fi
}

_git_repo() {
    if type -p __git_ps1; then
#        branch=$(__git_ps1 '%s')
        branch=$(__git_ps1)
        if [ -n "$branch" ]; then 
            subdir=$(git rev-parse --show-prefix 2>/dev/null)
            subdir="${subdir%/}" 
            predir="${PWD%/$subdir}"
            echo -ne "${predir#~}/${subdir}"
        else
            echo -ne ""
        fi
    fi
}

_git_repo_path() {
    if type -p __git_ps1; then
#        branch=$(__git_ps1 '%s')
        branch=$(__git_ps1)
        if [ -n "$branch" ]; then 
            n_remote="$(git remote | wc -l)"
            if [ $n_remote -eq 0 ]; then 
            # no remote repo, no backup red
                c_rem="[1;31m"
            elif [ $n_remote -eq 1 ]; then
            # single remote repo green
                c_rem="[1;32m"
            else
            # multiple remote repo purple
                c_rem="[1;35m"
            fi

            status=$(git status 2> /dev/null)
            if $(echo $status | grep 'added to commit' &> /dev/null); then
            # If we have modified files but no index (blue)
               c_stat="[1;34m"
            else
                if $(echo $status | grep 'to be committed' &> /dev/null); then
                # If we have files in index (red)
                   c_stat="[1;31m"
                else
                # If we are completely clean (green)
                   c_stat="[1;32m"
                fi
            fi

            subdir=$(git rev-parse --show-prefix 2>/dev/null)
            subdir="${subdir%/}" 
            predir="${PWD%/$subdir}"
            echo -ne "\033[01;34m~${predir#~}\033${c_rem}/${subdir}\033${c_stat}"
        else
            echo -ne "\033[01;34m"
        fi
    fi
}

# detect working directory relative to working tree root
pt_git_co() {
    if type -p __git_ps1; then
#        branch=$(__git_ps1 '%s')
        branch=$(__git_ps1)
        if [ -n "$branch" ]; then 
            if [ -n "$1" ]; then
                printf "$1" "${branch}"
            else
                printf "\n%s" "${branch}"
            fi
        else
            printf "%s" "~${PWD#~}"
        fi
    else
        printf "%s" "~${PWD#~}"
    fi
}

# set a fancy prompt (non-color, unless we know we "want" color)
case "$TERM" in
    xterm-color|*-256color) color_prompt=yes;;
esac

# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes

if [ -n "$force_color_prompt" ]; then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
	# We have color support; assume it's compliant with Ecma-48
	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
	# a case would tend to support setf rather than setaf.)
	color_prompt=yes
    elif [ "$TERM" = "cygwin" ]; then
	color_prompt=yes
    else
	color_prompt=
    fi
fi


if [ "$color_prompt" = yes ]; then
    #excape \[ non pritable char \]
    PS1='${debian_chroot:+($debian_chroot)}\[$(pt_user_co)\]\u\[\033[0m\]@\[$(pt_host_co)\]\h\[\033[0m\]:\[$(_git_repo_path)\]$(pt_git_co)\[\033[0m\]\$ '
#    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\n$(_git_repo)$(__git_ps1)\$ '
#    PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h:\w\a\]$PS1"
    ;;
*)
    ;;
esac

@carinlynchin

This comment has been minimized.

carinlynchin commented Oct 24, 2018

how come none of these git branch 2> things are working.. the only way i get my branch is with git rev-parse --abbrev-ref HEAD... thankfully someone else showed that method...https://trueskawka.github.io/blog/programming/2018/01/17/git-branch-in-your-prompt.html

@ldavidsp

This comment has been minimized.

ldavidsp commented Nov 11, 2018

PS1='\n\033[1m** Luis Solorzano \033[1m\u@\h (@) \033[1m** \n\033[1m\w [\033[0;36m]\033[1m$(__git_ps1)\n[\033[01;32m]└─[\033[01;32m]$[\033[0;32m] [\033[0m]'

image

@katiekeel

This comment has been minimized.

katiekeel commented Nov 19, 2018

@carinlynchin git branch only shows if you have a commit present in the git repo. I had the same problem and found the answer here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment