Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

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

export PS1="\
${PSColor_Off} \$?\
${PSColor_Off}${PSBGreen} \u\

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

How can I achieve this?

share|improve this question

marked as duplicate by manatwork, Anthon, jasonwryan, lesmana, vonbrand Jun 12 '13 at 11:47

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

up vote 3 down vote accepted

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.

share|improve this answer
Thanks! This is really useful. Will look into tput things, haven't seen those before. – Karlo Jun 12 '13 at 8:23
tput ensures that it won't produce ugly escape codes if your terminal doesn't support color. – l0b0 Jun 12 '13 at 8:26
I see. I just miss escaping of the nonprintable characters... Do you have that working? – Karlo Jun 12 '13 at 11:40
I'm not sure I understand what you mean. – l0b0 Jun 12 '13 at 12:37

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\] '
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.