Extend your bash PS1 with a git branch without breaking your prompt
Adding the current Git branch to Bash PS1 without breaking prompt width calculation.
- Published
- Updated
- Reading time
- 2 min read
I wanted my terminal prompt to show the current branch of the Git repository in which I was working.
Many guides explain how to add a branch name, but the first one I followed left me with a broken Bash prompt. It ignored newlines and behaved strangely whenever the prompt exceeded the terminal width.
The problem was that non-printing color sequences confused Bash’s prompt-width calculation. Wrapping those sequences in \[ and \] tells Bash not to count them as visible characters.
The following commented snippet extends ~/.bash_login, or another Bash startup file that contains user-specific configuration:
# write a function to compute the current git branch
parse_git_branch() {
local b=$(git symbolic-ref HEAD 2> /dev/null)
echo -n "${b#refs/heads/}"
}
# set the PS1 variable
PS1="\w\[\e[0;33;49m\]\$(parse_git_branch)\[\e[0;0m\]$ "
# on any regular directory it will output:
# /path/to/directory$ [PROMPT]
# on a git repository it will output:
# /path/to/directory(branch_name_in_yellow)$ [PROMPT]Understanding the PS1 components
\winserts the full path to the current directory.\Winserts the name of the current directory.\[begins a non-printing-character escape sequence.\]ends a non-printing-character escape sequence.\einserts an escape character, much like\033.\e[X;Y;Zmbegins a Bash color sequence whose values style all subsequent characters.
Xselects the effect:0resets it,1increases brightness,4underlines,5blinks,7swaps the foreground and background, and8hides the text.
Yselects the foreground color:30is black,31red,32green,33yellow,34blue,35magenta,36cyan,37white, and39the default.
Zselects the background color by adding ten to the corresponding foreground code; for example,40is black.\e[0;0mresets the color so that subsequent characters use their previous appearance.\$(function_name)inserts the output of a function call.
The rule
Always wrap color sequences in non-printing-character escape brackets.