I want my prompt to show the exit status of the last command, so I set my PS1 to this:
PS1="$? > "
But it always prints 0 >
.
Even when I run false
, for example, the prompt does not prints 1 >
or whatever the exit status is.
Why does this occur?
EDIT:
I tried to use a function to set my prompt, testing whether the exit status was greater than 0, so it will not print 0 >
always, only when the exit status is nonzero.
promptcmd() {
_EXIT=$?
test $_EXIT -gt 0 && printf "\e[1;31m [$_EXIT]"
printf "\e[0m ❯ "
unset _EXIT
}
PS1="$(promptcmd)"
But it also does not work.
$?
was expanded when you defined PS1
, because you used double quotes.
You can use single quotes to defer expansion until PS1
is displayed:
PS1='$? > '
This kind of "double expansion" is not a property of parameters in general, but a result of how the shell uses the value of PS1
. echo "$PS1"
will still show the literal string $? >
, but when the shell displays the prompt, it will expand any parameter expansions found in the value.