#!/usr/bin/env bash
# The $? variable holds the exit code from the last command
# Typically we use 0 for a success.
# Values 1 - 255 are used for other errors.
# There are some commonly used error codes such as:
# 127 for command not found
# 128 for invalid exit argument
# The man command may tell you the meanings of various exit codes depending on the command.
# Otherwise, you may use internet to search for them.
# Example:
# Here it should print 0 as the last exit code since nothing comes before this in the script.
echo Holds the last exit code: $?
# Example:
echo "Example 1: ls -a ."
ls -a .
echo Exit code from ls $?
echo
# Example:
echo "Example 2: not a real command"
notacommand -abcdefg . # causes code 127
echo $? # exit code 127 command not found
echo
# Example:
# One form of handling errors is with the exit code
echo "Example 3: Handling Errors with Exit Codes"
ls notrealdir # an intentionally fake directory, exit code 1
if [ $? -gt 0 ] # you can get more specific for specific errors
then
echo "Handled Error"
else
echo "ls executed successfully"
fi