Adding git branch on the Bash command prompt
Asked Answered
D

16

226

I tried adding the git branch I'm currently working on (checked-out) on the bash prompt without success.. (while keeping my current path which shows the active directory/file intact) I have a .bashrc file on my home, but I also saw many people mentioning the .profile file..

Dyslalia answered 8/4, 2013 at 15:41 Comment(6)
i think this would be better asked in the unix/linux exchange.Sheryl
I've tried like 10 different how-tos, some of them worked but I got the git branch and lost the working directory/path I had before..Dyslalia
Git 1.9.3+ brings an interesting way to display the branch: see my answer belowChoroid
Thanks VonC! Using this one since a couple of months now, great!Dyslalia
@cole busby apparently not.Dyslalia
@GeorgeKatsanos four years sure showed me :pSheryl
C
253

git 1.9.3 or later: use __git_ps1

Git provides a shell script called git-prompt.sh, which includes a function __git_ps1 that

prints text to add to bash PS1 prompt (includes branch name)

Its most basic usage is:

$ __git_ps1
(master)

It also takes an optional format string:

$ __git_ps1 'git:[%s]'
git:[master]

How to Get It

First, copy the file to somewhere (e.g. ~/.git-prompt.sh).

Option 1: use an existing copy on your filesystem. Example (Mac OS X 10.15):

$ find / -name 'git-prompt.sh' -type f -print -quit 2>/dev/null
/Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh

Option 2: Pull the script from GitHub.

Next, add the following line to your .bashrc/.zshrc:

source ~/.git-prompt.sh

Finally, change your PS1 to call __git_ps1 as command-substitution:

Bash:

PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

Zsh:

setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

Maksym Kosenko adds in the comments:

An interesting point: if you have a call of __git_ps1 function in your .bashrc file and there is a function named test somewhere in the same file, the last one will be executed automatically together with any git action.
It seems like inside of __git_ps1 there is a call of some test function which is obviously overridden by your custom one.


git < 1.9.3

But note that only git 1.9.3 (May 2014) or later allows you to safely display that branch name(!)

See commit 8976500 by Richard Hansen (richardhansen):

Both bash and zsh subject the value of PS1 to parameter expansion, command substitution, and arithmetic expansion.

Rather than include the raw, unescaped branch name in PS1 when running in two- or three-argument mode, construct PS1 to reference a variable that holds the branch name.

Because the shells do not recursively expand, this avoids arbitrary code execution by specially-crafted branch names such as

'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.

What devious mind would name a branch like that? ;) (Beside a Mom as in xkcd)

More Examples

still_dreaming_1 reports in the comments:

This seems to work great if you want a color prompt with xterm (in my .bashrc):

PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\03‌​3[01;34m\]\w\[\033[00m\]$(__git_ps1)\$ ' 

Everything is a different color, including the branch.

In Linux Mint 17.3 Cinnamon 64-bit:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ ' 

As noted by J'e in the comments

Ubuntu

Modify PS1 assignments in your bashrc with,

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\033[0;32m$(__git_ps1 " (%s)")\033[0m\$ '

# ---AND--- 

PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1 " (%s)")\$ '
Choroid answered 12/7, 2014 at 19:16 Comment(17)
how you can set the prompt to current git branch when you are actually in a git repo. So if you are in a normal directory it shows normal prompt.Gynecium
@ZubairAlam by setting the PS1 variable in your .bashrc, as mentioned in the answer.Choroid
This makes my colors go away in my terminal. I am using Linux Mint 17.2 and I downloaded the newest git-prompt.sh file from the git repository. But my git version is only 1.9.1 because that is the version Mint is on for some reason...Worth
@Worth you can upgrade or compile git very easily though: https://mcmap.net/q/13076/-upgrading-git-from-the-source-repository-in-ubuntuChoroid
@Choroid Thanks for the tip! I am on the latest version of git now, 2.6.2. I also made sure to copy the .git-prompt.sh file from that version. I am happy to be on the latest version of git now. However, this still makes my terminal start up without colors :(Worth
@Worth is this a classic bash terminal? Do you have git config --global color.ui set to always?Choroid
This seems to work great if you want a color a color prompt with xterm (in by .bashrc): PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]$(__git_ps1)\$' Everything is a different color, including the branch.Worth
@Worth great! I have included your comment in the answer for more visibility.Choroid
I added and it really works except, when I go to a repository it also shows this error: Usage: core.py [options] core.py: error: no such option: -nNeoimpressionism
That PS1 I posted no longer displays correctly for me in Linux Mint 17.3 Cinnamon 64-bit, but this does: PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ 'Worth
@Worth Thank you for the feedback (again): I have included it in the answer for more visibility.Choroid
Current master is at github.com/git/git/blob/master/contrib/completion/git-prompt.sh - I think we should link to that in the answer, in case an exploit is found in the future? Also: I had to escape the $ and " in my PS1 line, but that's probably due to its complexity.Appellate
@Appellate Good point: I have included the latest master version in this (now 5 years old answer)Choroid
For Ubuntu, there is a PS1 assignment section in the bashrc inside an if statement. modify each of the PS1 assignments in your with, PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\033[0;32m$(__git_ps1 " (%s)")\033[0m\$ ' ---AND--- PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(__git_ps1 " (%s)")\$ 'Cassimere
@J'e Thank you for the feedback. I have included your comment in the answer for more visibility.Choroid
An interesting point: if you have a call of __git_ps1 function in your .bashrc file and there is a function named test somewhere in the same file, the last one will be executed automatically together with any git action. It seems like inside of __git_ps1 there is a call of some test function which is obviously overridden by your custom one.Gayomart
@MaksymKosenko Interesting, thank you for the feedback. I have included your comment in the answer for more visibility.Choroid
H
79

Follow the steps as below: (Linux)

Edit the file ~/.bashrc, to enter following lines at its end (In case, of Mac, file would be ~/.bash_profile)

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

Now, start the new terminal window, and try entering to any git-repo. The current branch would be shown, with the prompt.

4 More Info - MAC/Linux

Hulse answered 5/2, 2016 at 7:27 Comment(14)
I don't think it's necessary to change the ~/.bash_profile instead of ~/.bashrc on OSX.Mathews
Please see apple.stackexchange.com/questions/119711/… AND apple.stackexchange.com/questions/51036/….Hulse
For colour consider changing the "git branch" to be "git -c color.ui=always branch" in parse_git_branch above. It has the same colour that git branch uses to highlight the current branch.Rhona
Inspired by you, but I like my working directory to be the full path (\w) with blue highlighting. Example: gist.github.com/rmharrison/1885ef6bbb0226eb7b42e2135d5eeca2Sabadell
For MAC I had to eliminate the escape before the $(parse_git_branch) to get this to work so : PS1="\u@\h \W\[\033[32m\]$(parse_git_branch)\[\033[00m\] $ ". Although I am not using 'export' in front of PS1 either.Wayfaring
On Mac, this worked on for git branch 2>/dev/null | sed -e 's/^\* \(.*\)/ (\1)/p' -nDesk
@Wayfaring if I remove the escape before the $ the prompt keeps displaying the branch value when the shell was initialized. Aka if I change the branch it keeps displaying the old one.Boulogne
Not sure what to tell you @Boulogne mine is still like that and works for me. I would suspect that your parse_git_branch() function might have a bug, try running that command by itself on different branches to see what it returnsWayfaring
@Wayfaring if I leave the escape slash before $ it works just fine.Boulogne
@Boulogne I think it must be the 2nd part of that comment. I'm not using 'export' before 'PS1' in my profile. Using 'export' would require that the escape be used.Wayfaring
If you don't like sed, you can instead do git branch -q --show-current 2>/dev/null, which only displays the current branch with no extra characters. Note: cannot auto color, instead you need to color it manually in your PS1 expression.Treadle
you need to surround the function with "": parse_git_branch`Pasteur
Much simpler and works in RedHat tooEllette
This should be the accepted answer bc of its simplicity.Persian
P
44

1- If you don't have bash-completion ... : sudo apt-get install bash-completion

2- Edit your .bashrc file and check (or add) :

if [ -f /etc/bash_completion ]; then
  . /etc/bash_completion
fi

3- ... before your prompt line : export PS1='$(__git_ps1) \w\$ '
(__git_ps1 will show your git branch)

4- do source .bashrc

EDIT :

Further readings : Don’t Reinvent the Wheel

Poliomyelitis answered 13/2, 2014 at 22:27 Comment(4)
this seems to be the only way it works for me using a homestead/vagrant machineLicha
Works fine in ubuntu 16.04Goldbrick
The "Don't Reinvent the Wheel" link is sadly broken.Voracious
@TaylorR I have restored the link.Choroid
C
40

Here is how I configured the prompt to display Git status:

Get git-prompt script:

curl -o ~/.git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

And customize your prompt adding the following code in your .bashrc file:

# Load Git functions
source ~/.git-prompt.sh

# Syntactic sugar for ANSI escape sequences
txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# Prompt variables
PROMPT_BEFORE="$txtcyn\u@\h $txtwht\w$txtrst"
PROMPT_AFTER="\\n\\\$ "

# Prompt command
PROMPT_COMMAND='__git_ps1 "$PROMPT_BEFORE" "$PROMPT_AFTER"'

# Git prompt features (read ~/.git-prompt.sh for reference)
export GIT_PS1_SHOWDIRTYSTATE="true"
export GIT_PS1_SHOWSTASHSTATE="true"
export GIT_PS1_SHOWUNTRACKEDFILES="true"
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS="true"

If you want to find out more, you can get all the dotfiles here: https://github.com/jamming/dotfiles

Chook answered 12/3, 2015 at 21:12 Comment(4)
Best answer so far.Remove
@Hesam You can change the PROMPT_BEFORE environment variable and remove the $txtwht\w I don't know it by heart, but I guess it does the trickChook
It works on my mac but shows the branch name like (master *$%=)Add
Those symbols resemble the state of the branch, ie: $ means that there are stashed changes, and = means that the latest commit was pushed to the remote tracked branchChook
U
11

For mac, this works really well: http://martinfitzpatrick.name/article/add-git-branch-name-to-terminal-prompt-mac/:

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

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
Unveiling answered 24/12, 2015 at 9:26 Comment(0)
M
8
root:~/project#  -> root:~/project(dev)# 

add the following code to the end of your ~/.bashrc

force_color_prompt=yes
color_prompt=yes
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;31m\]$(parse_git_branch)\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w$(parse_git_branch)\$ '
fi
unset color_prompt force_color_prompt
Marylandmarylee answered 17/1, 2019 at 6:51 Comment(1)
I like that this doesn't screw up the colorization when the current dir isn't part of a repo, as with other answers.Complain
B
8

At first, open your Bash Profile in your home directory. The easiest way to open & edit your bash_profile using your default editor.

For example, I open it using the VS Code using this command: code .bash_profile.

Then just paste the following codes to your Bash.

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

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

The function

parse_git_branch()

will fetch the branch name & then through PS1 you can show it in your terminal.

Here,

\u = Username

@ = Static Text

\h = Computer Name

\w = Current Directory

$ = Static Text

You can change or remove these variables for more customization.


If you use Git for the first time in terminal or instantly after configuration, maybe sometimes you can not see the branch name.

If you get this problem, don't worry. In that case, just make a sample repository and commit it after some changes. When the commit command will execute once, the terminal will find git branch from then.


Screenshot: Git Branch in Terminal

Bufordbug answered 17/4, 2019 at 0:56 Comment(0)
A
6

I wanted a clean solution that appended to the existing prompt instead of replacing it. As with other solutions, add this to the bottom of your .bashrc

# function
parse_git_branch() {
  if [ -n "$(git rev-parse --git-dir 2> /dev/null)" ]; then
    echo ">> $(git rev-parse --abbrev-ref HEAD) >>"
  fi
}

# environment customization
export PS1="\$(parse_git_branch)\n$PS1"

This setup yields a prompt that looks like

>> branchname >>
user@host:~/current/path$

Additionally I like to add a bit of color to the prompt so it stands out better like so

export PS1="\e[0;36m\$(parse_git_branch)\e[0m\n$PS1"

which causes the name of the branch to appear in CYAN

Ajay answered 9/11, 2021 at 2:11 Comment(0)
D
2
vim ~/.bash

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\] $"

To reflect latest changes run following command

source ~/.bashrc

Output:-

chandrakant@NDL41104 ~/Chandrakant/CodeBase/LaravelApp (development) $
Decanal answered 24/4, 2018 at 13:56 Comment(0)
V
1

If you use the fish shell its quite straight forward. fish is an interactive shell which comes with lots of goodies. You can install it using apt-get.

sudo apt-get install fish

you can then change the prompt setting using

> fish_config 
Web config started at 'http://localhost:8001/'. Hit enter to stop.
Created new window in existing browser session.

now go to http://localhost:8001/ open the prompt tab and choose the classic + git option

enter image description here

Now click on the use prompt button and you are set.

Visceral answered 23/5, 2016 at 8:32 Comment(0)
N
0
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1='\[\e]0;\w\a\]\n\[\e[32m\]\u@\h \[\e[33m\]\w\[\e[0m\]$(parse_git_branch)\n\$ '
Nostril answered 15/2, 2018 at 11:56 Comment(1)
Eww, really don't put naked terminal escapes in there; use tput like any sane person.Ashlieashlin
A
0

Follow the below steps to show the name of the branch of your GIT repo in ubuntu terminal:

step1: open terminal and edit .bashrc using the following command.

vi .bashrc

step2: add the following line at the end of the .bashrc file :

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

export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

step3: source .bashrc in the root (home) directory by doing:

/rootfolder:~$ source .bashrc

Step4: Restart and open the terminal and check the cmd. Navigate to your GIt repo directory path and you are done. :)

Adame answered 19/4, 2018 at 7:55 Comment(0)
D
0

Here is a simple clean version that I use: link

enter image description here

Dockhand answered 7/4, 2019 at 10:1 Comment(0)
I
0

check this repo: https://github.com/magicmonty/bash-git-prompt
This prompt is a port of the "Informative git prompt for zsh"

via Git clone Clone this repository to your home directory.

git clone https://github.com/magicmonty/bash-git-prompt.git ~/.bash-git-prompt --depth=1

Add to the ~/.bashrc:

if [ -f "$HOME/.bash-git-prompt/gitprompt.sh" ]; then
    GIT_PROMPT_ONLY_IN_REPO=1
    source $HOME/.bash-git-prompt/gitprompt.sh
fi
Indistinguishable answered 10/11, 2022 at 18:40 Comment(0)
A
0

Using ZSH I usually do:

export PROMPT="\$vcs_info_msg_0_"
# outputs the name of the branch like `[develop]`

Where you can obviously add your other stuff

Another workaround is:

curr_branch() {
    # get current branch
    git branch --show-current
    # outputs just the name of the branch, like `develop`
}
# bash
export PS1="\$(curr_branch)"
# zsh
export PROMPT="\$(curr_branch)"
Ambrosine answered 19/4, 2023 at 10:32 Comment(0)
L
-1

I have tried a small script in python that goes in a bin folder.... 'gitprompt' file

#!/usr/bin/env python
import subprocess, os
s = os.path.join(os.getcwd(), '.git')
def cut(cmd):
    ret=''
    half=0
    record = False
    for c in cmd:
        if c == "\n":
            if not (record):
                pass
            else:
                break
        if (record) and c!="\n":
            ret = ret + c
        if c=='*':
            half=0.5
        if c==' ':
            if half == 0.5:
                half = 1
        if half == 1:
            record = True
    return ret
if (os.path.isdir(s)):
    out = subprocess.check_output("git branch",shell=True)
    print cut(out)
else:
    print "-"

Make it executable and stuff

Then adjust the bash prompt accordingly like :

\u:\w--[$(gitprompt)] \$ 
Liaotung answered 4/7, 2015 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.