Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

3 Answers 3

up vote 3 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.