Every command in bash returns an exit status. Exit statuses are represented as integers ranging from 0 to 255. These integers, however, can be categorised under 2 categories:
You can easily check the exit code of a previous command by using the defined global variable $?
. It stores the exit code that the call/command before it returned:
function failure_fn() {
echo "I will fail"
return 1
}
function main_fn() {
echo "Just a regular echo with exit 0 of course"
echo "$?" # 0
failure_fn
echo "$?" # 1
}
main_fn
&&
and ||
operator to check exit codeThere are two operators which we can use in conjunction with an exit code in our code.
&&
: this only evaluates the right-hand side code if the left-hand side command has a zero exit code||
: this only evaluates the right-hand side code if the left-hand side command has a non-zero exit codeThe example below will check if a record is in a text file and check if we have an audio playing program:
function can_play_music() {
if command -v aplay > /dev/null; then
return 1
fi
}
function does_have_record() {
grep -q "$record" my_records.txt && echo "I found the record"
}
function play_record() {
record="Kind of Blue"
does_have_record
record="The Fat of The Land"
does_have_record || echo "$record not found! Shame on you!"
can_play_music || exit 1
}
play_record