Find the exit status of a previous command in Bash

0

Most programs will return an exit status of 0 if the program was successful, while a non-zero exit status usually indicates an error. You can find the exit status or exit code of the previously executed command by accessing the “$?” shell variable.

$ COMMAND
$ echo $?

Typically when a command terminates on a fatal signal whose number is N, Bash uses the value 128+N as the exit status. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126.

You can also use the exit status in a conditional.

#!/bin/bash
COMMAND
STATUS=$?
if [ $STATUS -eq 0 ]; then
echo "Command Successful"
else
echo "Command Failed"
fi

Share.