1

I want to set a sub portion of my PS1 prompt string to a specific color/style that is chosen by passing into a bash function.

It is easy for me to explicitly put the color in the PS1 variable directly. However, when I to do this using a bash variable like $1 or like $MY_COLOR instead of getting a colored part of the prompt, I end up with the exact characters from the PS1 color code as part of the prompt itself.

Here is my example:

function set_git_branch_prompt()
{
   git_prompt_style="\\[\\e[1;35m\\]" # Default bold magenta
   if [[ $# != 0 ]]; then
     git_prompt_style="\\[\\e[$1m\\]"
   fi
   export PS1=$(echo "$PS1" | sed -r 's/(.*)\\n\\\$/\1$git_prompt_style\$(parse_git_branch)\\[\\e[00m\\]\\n\\\$/g')
}

Instead of the of the specified color (such as bold magenta) I end up with the characters such as \[\e[1;35m\] as part of the prompt.

How do I go about having PS1 interprete $git_prompt_style as the actual PS1 code and not explicit characters?

EmceeBC
  • 71
  • 4

1 Answers1

0

The following worked for me:

user_col="\[\033[01;32m\]"
PS1=$user_col'\u\$\[\e[00m\] '

The two strings (the value of user_col and the literal of the rest of the prompt) are just jammed together. No need for a plus sign or anything (adding a plus sign just makes it part of the prompt).

If you want to go for a multi-colored prompt, you can certainly do this. You just need to "drop out of" the literal prompt string with another ' when you want to specify a color, and use another ' to go "back in" afterwards.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39