12

I would like to print at every lauched command in zsh exit code value. E.g.

$ cat file_not_present
cat: file_not_present: No such file or directory
Exit code 1

I only know that I can print error code of last command launched in terminal with

$ echo $?

How can I do?

3 Answers3

12

Personally, I add %(?..%B(%?%)%b) to my $PROMPT, so that the exit status of the previous command be shown in bold in brackets if it was unsuccessful, which is less intrusive than printing the exit status of every command.

To print the exit status of every failing command, you can do:

TRAPERR() print -u2 Exit status: $?
$ false; false; (exit 123)
Exit status: 1
Exit status: 1
Exit status: 123
(123)$ 

(the (123)$ being from that $PROMPT mentioned above).

For every command:

TRAPDEBUG() print -u2 Exit status: $?

But that will likely get very annoying.

You can also print the exit status of the last command that was run with:

print_last_status() print -u2 Exit status: $?
precmd_functions+=(print_last_status)
$ false; (exit 123); true
Exit status: 0

Like for the $PROMPT approach, you only see the status of the last command run in the command line you sent at the previous prompt.

In any case, printing it on stderr (as I do above with -u2) will likely cause fewer problems than doing it on stdout. Doing print Exit status: $? > /dev/tty may be even better.

5

You can add any user defined function into precmd_functions:

print_status() echo $?
precmd_functions+=(print_status)

It is executed before every prompt, that means after the command.

thanasisp
  • 8,122
3

In zsh, you can use the precmd hook and do something like this (taken from this answer):

% PROMPT_COMMAND='printf "Exit code: %s\n" $?'
% precmd() { eval "$PROMPT_COMMAND" }
% cat file_not_present
cat: file_not_present: No such file or directory
Exit code: 1               

In bash, you can use the PROMPT_COMMAND variable for that:

$ PROMPT_COMMAND='printf "Exit code: %s\n" $?'
$ cat file_not_present
cat: file_not_present: No such file or directory
Exit code: 1
terdon
  • 242,166
  • 1
    Also, doing that ugly eval "$PROMPT_COMMAND" would only be for bash users trying to minimise differences when using zsh. Doing it the other way round (use PROMPT_COMMAND=precmd in bash and define precmd() for both) would seem cleaner to me. – Stéphane Chazelas May 26 '22 at 10:26
  • @StéphaneChazelas sounds reasonable. I don't use zsh myself, I just found that SU answer, checked that it works, and posted. – terdon May 26 '22 at 10:52