- Catalina
- Big Sur
- Monterey
- Ventura
- Sonoma
Open ~/.zshrc
in your favorite editor and add the following content to the bottom.
function parse_git_branch() {
git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF=$'%f'
COLOR_USR=$'%F{243}'
COLOR_DIR=$'%F{197}'
COLOR_GIT=$'%F{39}'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n ${COLOR_DIR}%~ ${COLOR_GIT}$(parse_git_branch)${COLOR_DEF} $ '
To reload and apply adjustments to the formatting use source ~/.zshrc
in the zsh shell.
- Thank you benP2ER for the useful additions in his comment
- Original gist by Jose Quintana: Add Git Branch Name to Terminal Prompt (Linux/Mac)
Thanks for the script.
I ran into some issues on my system (macOS Monterey 12.0.1; zsh 5.8). When I autocomplete paths or use the arrow key to scroll through previous commands the formatting gets screwed up. Turns out the issues occur because of the ANSI color codes.
Solution:
The zsh shell has its own Prompt Expensions with visual effects. For colors you use
%F
and%f
to escape the foreground color. (This also allows the usage of color aliases like%F{blue}This text is blue!%f
)Adjusted script:
Other Things:
To avoid non ascii characters causing this issue try wrapping them in a 'glitch' sequence which assumes everything inside is only one character long, like this:
%{👌%G%}
.To reload and apply adjustments to the formatting use
$ source ~/.zshrc
in the zsh shell.If you have a long working directory, you can shorten the path by only displaying the last n elements of the path. To display the last 2 elements replace
%~
with%2~
.I also didn't want 2 spaces displayed, when the current working directory is not a repository so I adjusted the spacings:
You could also shorten the script by removing the COLOR_... variables and using the extensions directly:
Hope this maybe helps anyone with the same issues.