Last failed command in bash

If the last command was executed without arguments, it'll be saved in the $_ variable. This normally contains the last argument of previous command - so if there were no arguments, the value of $_ is the last command itself.

Another option is to learn the details of last background command. As l0b0 wrote, $! holds its PID - so you can parse the output of ps $! (possibly with additional formating options to ps).


Use fc to get the previous command line. It is normally used to edit the previous command line in your favourite editor, but it has a "list" mode, too:

last_command="$(fc -nl -1)"


The DEBUG trap lets you execute a command right before any simple command execution. A string version of the command to execute (with words separated by spaces) is available in the BASH_COMMAND variable.

trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
…
echo "last command is $previous_command"

Note that previous_command will change every time you run a command, so save it to a variable in order to use it. If you want to know the previous command's return status as well, save both in a single command.

cmd=$previous_command ret=$?
if [ $ret -ne 0 ]; then echo "$cmd failed with error code $ret"; fi

If you only want to abort on a failed commands, use set -e to make your script exit on the first failed command. You can display the last command from the EXIT trap.

set -e
trap 'echo "exit $? due to $previous_command"' EXIT

An alternate approach that might work for some uses is to use set -x to print a trace of the script's execution and examine the last few lines of the trace.