DawsonMSchaffer
DawsonMSchaffer

Reputation: 149

Git branch name in Bash prompt

I have been trying to get the Git status on my bash prompt but haven't had any success. The color variables work so it's not them. Here is my PS1 and parse function.

PS1="${GREEN}ganymede@${BLUE}dawson:${ICYAN}\W${RESET}${IYELLOW} $(parse_git_branch) $ " 

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

What is missing from my PS1?

Thanks Dawson

Upvotes: 0

Views: 639

Answers (1)

torek
torek

Reputation: 489748

The line:

PS1="$anything"

or:

PS1="$(command)"

written this way means: evaluate $anything now or run command now, i.e., at the time you're setting the variable PS1. Let's suppose that $anything or command prints hello. The final result is:

PS1=hello

after which the prompt you'll get is the constant string hello.

You'd like PS1 to contain, among other things, the string $(parse_git_branch). That means you must quote the dollar sign, e.g.:

PS1=\$\(parse_git_branch\)

or:

PS1="\$(parse_git_branch)"

or:

PS1='$(parse_git_branch)'

If you're willing to let all $var expansions take place later, the single quote method is simple and effective. If you want some expansions to take place now, consider, e.g.:

PS1="${GREEN}ganymede@${BLUE}dawson:${ICYAN}\W${RESET}${IYELLOW} \$(parse_git_branch) $ " 

or:

PS1="${GREEN}ganymede@${BLUE}dawson:${ICYAN}\W${RESET}${IYELLOW} "'$(parse_git_branch) $ ' 

Note that the unquoted SPACE$SPACE in some of these is "safe" because $SPACE remains unchanged during expansion.

Upvotes: 5

Related Questions