This is what I use in my .bashrc
:
PS1_PROMPT() {
local e=$?
(( e )) && printf "$e|"
return $e
}
PS1='$(PS1_PROMPT)'"$PS1"
ibug@example:~ $ false
1|ibug@example:~ $ ^C
130|ibug@exame:~ $ true
ibug@example:~ $
This has the advantage over JoL's answer that the value of $?
is preserved after displaying (via return $e
). It's also basically a rework of Android's default /system/etc/mkshrc
that does the same job.
Note that $(PS1_PROMPT)
is enclosed in single quotes because $PS1
is evaluated every time it's printed, in addition to when set in a variable assignment expression, so single quotes prevents it from being evaluted right now and instead defers that to when printing.
Alternatively, as suggested by ilkkachu, you can make use of Bash PROMPT_COMMAND
special variable:
PS1_PROMPT() {
local e=$?
PROMPT_ECODE=
(( e )) && PROMPT_ECODE="$e|"
return $e
}
PROMPT_COMMAND=PS1_PROMPT
PS1='$PROMPT_ECODE'"$PS1"
This has one advantage that no subshell is spawned every time PS1 is printed.