Git branch & ZSH on MacOS

May 28, 2022

It can be very useful to show the git branch that is actually checked out when working with the terminal. To do so simply add the following code to the .zshrc file :

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

COLOR_DEF=$'\e[0m'
COLOR_USR=$'\e[38;5;243m'
COLOR_DIR=$'\e[38;5;197m'
COLOR_GIT=$'\e[38;5;39m'
setopt PROMPT_SUBST
export PROMPT='%{${COLOR_USR}%}%n %{${COLOR_DIR}%}%~ %{${COLOR_GIT}%}$(parse_git_branch)%{${COLOR_DEF}%} $ '

Note that in order to avoid extra spaces when using ctrl+R you need to enclose escape literals in %{...%}.

If the .zshrc file doesn't exist, you can create it by typing :

vim ~/.zshrc

Profile picture

Written by Olivier Bonnet who lives and works in Montreal writing a blog that nobody reads 🤪...

© Bonneto 2024