Print return value after program execution
I am wondering how to set option to auto print return value after every program execution in terminal without typing echo $?
.
Is it something that can be setup? Codeblocks has that feature.
Yes, there are two ways. One is to set PROMPT_COMMAND
in .bashrc
, the other - to set command substitution in PS1
for the echo $?
command.
Method 1:
From the bash manual page:
PROMPT_COMMAND
If set, the value is executed as a command prior to issuing each primary prompt.
Whatever you set this variable to, will be run before drawing the prompt each time. Demo:
$> PROMPT_COMMAND=" echo 'Last command exited with' \$? 'code' "
Last command exited with 0 code
$> ls /etc/passwd > /dev/null
Last command exited with 0 code
$> ls /etc/asdf > /dev/null
ls: cannot access /etc/asdf: No such file or directory
Last command exited with 2 code
$>
Note the use of \$?
. For permanent change, save it in .bashrc
Method 2
Suppose my PS1
prompt is set like this:
PS1='
user@ubuntu:$> '
If I want to run some program each time this prompt is redrawn on the screen (which is after each preceding command runs), I would need to use command substitution $(. . .)
and set it in the prompt like so:
PS1=' [ $? ]
user@ubuntu: $> '
Demo:
$> PS1=' [ $? ]
> $>_ '
[ 0 ]
$>_ ls /etc/passwd > /dev/null
[ 0 ]
$>_ ls /etc/asdf > /dev/null
ls: cannot access /etc/asdf: No such file or directory
[ 2 ]
$>_
Notice that I split my PS1 into two lines, top will have [ exitcode ]
and bottom $> <blank space>'
. That is why there is >
before $> '
on the second line (The leading >
is PS2
prompt for multiline commands ) . Alternatively, you could do something like this ( notice the $'...'
structure):
$> PS1=$'[ $? ] \n$> '
[ 0 ]
$>
A method which I picked from the Arch Wiki is to trap
ERR
. trap
is used in Bash to run commands when a signal is received, or for certain other events. An ERR
trap is ran whenever the current command line terminates with an error - the return value is not 0. (If it did terminate normally, the return value would obviously be 0.)
So, for example:
trap 'printf "\ncode %d\n\n" $?' ERR
Then:
$ echo foo
foo
$ false
code 1
$
(Note: no message after the echo
command which ran successfully - What does it mean when I type a command and the terminal does nothing?)
The Arch Wiki tip went ahead and colorized the message, so that you get a noticeable yellow message:
EC() { echo -e '\e[1;33m'code $?'\e[m\n'; }
trap EC ERR
Effect:
In effect, all I need to do is keep an eye out for a yellow code
in the output to know a command failed.