DEV Community

LocKtaR-o-DarK
LocKtaR-o-DarK

Posted on

How do I show the git branch with colours in Bash prompt?

in Ubuntu

sudo nano ~/.bashrc
# or on MacOS
sudo nano ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode

find this strings in .bashrc or .bash_profile on MacOS

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
Enter fullscreen mode Exit fullscreen mode

and replace it with:

full command prompt like ${username@hostname}

function parse_git_branch {
    git branch 2>/dev/null | grep '*' | sed 's/* //'
}

if [ "$color_prompt" = yes ]; then
    PS1="${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\] » \[\033[33m\]\$(parse_git_branch) \[\033[00m\]$ "
else
    PS1="${debian_chroot:+($debian_chroot)}\u@\h:\w » \$(parse_git_branch) $ "
fi
Enter fullscreen mode Exit fullscreen mode

short command prompt without ${username@hostname}

function parse_git_branch {
    git branch 2>/dev/null | grep '*' | sed 's/* //'
}

if [ "$color_prompt" = yes ]; then
    PS1="\[\033[01;34m\]\w\[\033[00m\] » \[\033[33m\]\$(parse_git_branch) \[\033[00m\]$ "
else
    PS1="\w » \$(parse_git_branch) $ "
fi
Enter fullscreen mode Exit fullscreen mode

short command prompt (only branch name)

function parse_git_branch {
    git branch 2>/dev/null | grep '*' | sed 's/* //'
}

if [ "$color_prompt" = yes ]; then
    PS1="\$(parse_git_branch) \[\033[00m\]$ "
else
    PS1="\$(parse_git_branch) $ "
fi
Enter fullscreen mode Exit fullscreen mode

show current branch

git branch --show-current
git rev-parse --abbrev-ref HEAD
Enter fullscreen mode Exit fullscreen mode

in Windows Git Bash

# change directory to user home (~)
cd
# or
cd ~

# list .bashrc file
ll .bashrc
# or on MacOS
ll .bash_profile

# create .bashrc
touch ~/.bashrc
# or on MacOS
touch ~/.bash_profile

# add content
nano ~/.bashrc
# or on MacOS
nano ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode

and paste any string you want from the example above into the ~/.bashrc or ~/.bash_profile file

Press Alt+X -> Y -> Enter

After save your settings, update your shell environment with

source ~/.bashrc
# or on MacOS
source ~/.bash_profile
Enter fullscreen mode Exit fullscreen mode

ZSH

For zsh you can use:

function parse*git_branch {
    git branch 2>/dev/null | grep '*' | sed 's/\_ //'
}

setopt PROMPT_SUBST
PROMPT='%n@%m %1~ %F{yellow}$(parse_git_branch)%f %# '
Enter fullscreen mode Exit fullscreen mode

This script can be added to ~/.zshrc. After add it use source ~/.zshrc, for update your shell environment.

The command line prompt will now display the current git branch if you are in a git repository.

Top comments (0)