To get the exit code of a command type echo $?
at the command prompt. In the following example a file is printed to the terminal using the cat command.
cat file.txt hello world echo $? 0
The command was successful. The file exists and there are no errors in reading the file or writing it to the terminal. The exit code is therefor 0.
cat doesnotexist.txt cat: doesnotexist.txt: No such file or directory echo $? 1
The exit code is 1 as the operation was not successful.
To use exit codes in scripts an “if” statement can be used to see if an operation was successful.
#!/bin/bash cat file.txt if [ $? -eq 0 ] then echo "The script ran ok" exit 0 else echo "The script failed" >&2 exit 1 fi
To set an exit code in a script use “exit0” where “0” is the number you want to return. In the following example a shell script exits with a “1”. This file is saved as “exit.sh”.
#!/bin/bash exit 1
bash exit.sh echo $? 1