Prepare the git_ps1
like this:
git_ps1=$(git branch 2>/dev/null | grep '*')
git_ps1="${git_ps1:+ (${git_ps1/#\* /}) }"
## ^space ^space
## Change the spaces if you like it other ways.
git_ps1
will be like (master)
, with spaces at both ends; and a complete empty string when git_ps1
is not set (for non-git dir) . Now you can just use the $git_ps1
variable to insert it anywhere you like.
Explanation:
git_ps1="${git_ps1:+ (${git_ps1/#\* /}) }"
is a conditional variable assignment.
if git_ps1
is set then it will be equal to (${git_ps1/#\* /})
, otherwise it will remain empty.
${git_ps1/#\* /}
cuts the *
and space from the beginning of $git_ps1
Example Usage:
__git_ps1(){
git_ps1=$(git branch 2>/dev/null | grep '*')
git_ps1="${git_ps1:+ (${git_ps1/#\* /})}"
echo "$git_ps1"
}
if [ "$color_prompt" = yes ]; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[00m\]\[\033[01;34m\]\w\[\033[00m\]$(__git_ps1) \[\033[1;32m\]>\[\033[00m\]\[\033[1;32m\]>\[\033[00m\]\[\033[1;32m\]>\[\033[00m\] '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
This gives me a prompt like this one:
