bash – Display Non-Zero Return Status in PS1

bashprompt

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.

Example:

sd ~ $ false
1 sd ~ $ true
sd ~ $ 

Best Answer

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 %~ %# '
Related Question