1

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.

Seninha
  • 329
  • 1
  • 12

1 Answers1

1

$? 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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Thanks, the example I gave was just a snipped that I tried to set my PS1 to, I edited the question to put my actual PS1, which also does not work – Seninha Feb 12 '20 at 12:31
  • Again, `promptcmd` is run when you *define* `PS1`, so you are hard-coding the value of `$?` at that time; you still need single quotes to defer the command substitution. But see the answer for a better way to use `promptcmd`. – chepner Feb 12 '20 at 12:36
  • I just set my PS1 to `'$(promptcmd)'` and it worked, thanks. I don't think mksh supports `PROMPT_COMMAND`, this is a bash feature (at least mksh manpage does not mention it). – Seninha Feb 12 '20 at 12:40
  • Oh, sorry, I keep overlooking that tag. – chepner Feb 12 '20 at 12:41
  • Be sure to read the entry for `PS1` in the man page for `mksh` regarding escape sequences. In `bash`, you would wrap them in `\[...\]`; in `mksh`, it looks like you specify a delimiter at the beginning of the prompt that you can use to wrap escape sequences. I don't have `mksh` available to test, though. – chepner Feb 12 '20 at 12:46