How to use Exit Codes in Conditional Statements in Shell Scripts

The exit Command

You can use the exit command in a script to force the shell to terminate with whatever exit code you provide. For example, exit 1 will cause the script to terminate with a failure status. If you don’t provide a number, exit will terminate with the exit code of the last command that was run.

Using exit codes in Conditional Statements

Conditional statements like if…else are good at handling process exit codes. For example:

chmod 888 file 2> /dev/null

if [ $? -eq 0 ]
then
    echo "Permissions set successfully."
    exit 0 
else
    echo "Could not set permissions."
    exit 1 
fi

If the chmod command exits with a code of 0, then the success message is echoed to the screen, and any other process that executes this script will receive that exit code because of the exit command. Likewise, if the exit code is 1, then a custom error message is echoed to the screen. The default error message is suppressed, as it is being redirected to the null device.

Related Post