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

I want to include the return status in my prompt. (Easy add '$? ', right?)

However, I only want the status returned (and trailing space) if non-zero.


sd ~ $ false
1 sd ~ $ true
sd ~ $ 
share|improve this question
Cross-site dupe: stackoverflow.com/q/5946873/3821804 – GingerPlusPlus Mar 21 at 18:16
up vote 4 down vote accepted

Make sure that the promptvars option is on (it is by default). Then put whatever code you like in PROMPT_COMMAND to define a variable containing exactly what you want in the prompt.

PROMPT_COMMAND='prompt_status="$? "; if [[ $prompt_status == "0 " ]]; then prompt_status=; fi'
PS1='$prompt_status\h \w \$ '

In zsh you could use its conditional construct in PS1 (bash has no equivalent).

PS1='%(?,,%? )%m %~ %# '
share|improve this answer

The best I can have is obtained by


where I added a : as a separator, so not exactly what is in the question.

share|improve this answer

It is not required to use PROMPT_COMMAND. Here it does needless complications. All you have to do is define this function:

    [ $? = 0 ] && return
    echo -n "${?} "

And then set PS1 like this:

shopt -s promptvars

Evaluation of prompt_status() inside subshell protects $? from being changed.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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