Consider this PS1
PS1='\n${_:+$? }$ '
Here is the result of a few commands
$ [ 2 = 2 ]
0 $ [ 2 = 3 ]
1 $
1 $
The first line shows no status as expected, and the next two lines show the correct exit code. However on line 3 only Enter was pressed, so I would like the status to go away, like line 1. How can I do this?
Here's a funny, very simple possibility: it uses the
\#
escape sequence ofPS1
together with parameter expansions (and the way Bash expands its prompt).The escape sequence
\#
expands to the command number of the command to be executed. This is incremented each time a command has actually been executed. Try it:Now, each time a prompt is to be displayed, Bash first expands the escape sequences found in
PS1
, then (provided the shell optionpromptvars
is set, which is the default), this string is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal.The trick is then to have an array that will have the k-th field set (to the empty string) whenever the (k-1)-th command is executed. Then, using appropriate parameter expansions, we'll be able to detect when these fields are set and to display the return code of the previous command if the field isn't set. If you want to call this array
__cmdnbary
, just do:Look:
To qualify for the shortest answer challenge:
that's 31 characters.
Don't use this, of course, as
a
is a too trivial name; also,\$
might be better than$
.Seems you don't like that the initial prompt is
0 $
; you can very easily modify this by initializing the array__cmdnbary
appropriately: you'll put this somewhere in your configuration file: