3

I have my current PS1 as follows. The $? output is really useful (second line).

export PS1="\
${PSOn_Blue}${PSBWhite}\t\
${PSColor_Off} \$?\
${PSColor_Off}${PSBGreen} \u\
${PSColor_Off}${PSWhite}@\
${PSColor_Off}${hostcolor}\h\
${PSColor_Off}:\
${PSBGreen}\w\
${PSColor_Off}\$\
 "

It would be even nicer if the return code ($?) would be red on non-zero output.

How can I achieve this?

Anthon
  • 79,293
Karel
  • 1,468

2 Answers2

5

I use this:

BOLD_FORMAT="${BOLD_FORMAT-$(color_enabled && tput bold)}"
ERROR_FORMAT="${ERROR_FORMAT-$(color_enabled && tput setaf 1)}"
RESET_FORMAT="${RESET_FORMAT-$(color_enabled && tput sgr0)}"

PS1='$(exit_code=$?; [ $exit_code -eq 0 ] || printf %s $BOLD_FORMAT $ERROR_FORMAT $exit_code $RESET_FORMAT " ")'

Concatenate that with the rest of your $PS1, but make sure you still use the single quotes, otherwise it won't work, and you should be golden. If you want to display the exit code even if it's zero, simply remove the [ $exit_code -eq 0 ] || bit.

l0b0
  • 51,350
1

This would show the basename of the working directory (\W) in green or red:

PS1='\[\e[$([[ $? = 0 ]] && printf 32 || printf 31);1m\]\W\[\e[m\] '
Lri
  • 5,223