Is it possible to pre-evaluate the value in bash PS1?

I am trying to create a Bash prompt that will have both my git branch information (using __git_ps1 from git bash -completion) and a slightly colored emoticon to indicate whether the last run command was successful.

A smiley is created using this technique that I found here on SO:

SMILEY="${GREEN}:)${COLOR_NONE}" FROWNY="${RED}:(${COLOR_NONE}" STATUS_EMOTICON="if [ \$? = 0 ]; then echo \"${SMILEY}\"; else echo \"${FROWNY}\"; fi" 

Here's the prompt string I want to use:

 export PS1="[\t]${RED}[\ u@ $MACHINE:${BOLD_CYAN}\w${GREEN}\$(__git_ps1 ' %s')${RED}]${COLOR_NONE} \`${STATUS_EMOTICON}\`\n$ " 

Unfortunately, it seems like programs running __git_ps1 override the value of $? , and in the end I get a green emoticon, even after running false .

Call __git_ps1 ...

 export PS1="[\t]${RED}[\ u@ $MACHINE:${BOLD_CYAN}\w${RED}]${COLOR_NONE} \`${STATUS_EMOTICON}\`\n$ " 

... makes the emoticon work correctly.

So what I apparently need to do is evaluate ${STATUS_EMOTICON} before running __git_ps1 , but include the estimated value after __git_ps1 output. Is it possible?

+4
source share
1 answer

Do not put $(cmd) or `cmd` directly in your PS1 . Instead use Bash PROMPT_COMMAND var. I usually set the _PS1_cmd function and set PROMPT_COMMAND=_PS1_cmd . Then in _PS1_cmd , I set different characters that I would like to include in PS1 . For instance:

 THE-OLD-PROMPT # cat prompt.rc function _PS1_cmd() { local saveExit=$? # This non-zero exit will not affect $? on command line g_git_ps1=$( echo TESTING; exit 1 ) if (( saveExit )); then g_smiley=':(' else g_smiley=':)' fi # Seems like this is not necessary, at least with bash 4.2.37. But # to be safe, always return it. return $saveExit } PROMPT_COMMAND=_PS1_cmd PS1='$g_git_ps1 $g_smiley ' THE-OLD-PROMPT # source ./prompt.rc TESTING :) ( exit 123 ) TESTING :( echo $? 123 TESTING :) echo $? 0 TESTING :) 
+6
source

All Articles