Getting exit code of last shell command in another script Getting exit code of last shell command in another script bash bash

Getting exit code of last shell command in another script


You'd really need to use a shell function in order to accomplish that. For a simple script like that it should be pretty easy to have it working in both zsh and bash. Just place the following in a file:

my_notify() {  echo "exit code: $?"  echo "PPID: $PPID"}

Then source that file from your shell startup files. Although since that would be run from within your interactive shell, you may want to use $$ rather than $PPID.


It is incompatible. $? only exists within the current shell; if you want it available in subprocesses then you must copy it to an environment variable.

The alternative is to write a shell function that uses it in some way instead.


One method to implement this could be to use EOF tag and a master script which will create your my_notify script.


#!/bin/bashif [ -f my_notify ] ; thenrm -rf my_notifyfiif [ -f my_temp ] ; thenrm -rf my_tempfiretval=`ls non_existent_file &> /dev/null  ; echo $?`ppid=$PPIDecho "retval=$retval" echo "ppid=$ppid" cat >> my_notify << 'EOF'#!/bin/bashecho "exit code: $retval"echo " PPID =$ppid"EOFsh my_notify 

You can refine this script for your purpose.