Exit Codes
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 3 of 39.
Every command ends with an exit code, a number from 0 to 255. 0 means success; any other number means a failure, and the number can say which kind. The variable $? holds the exit code of the command that ran last, so read it right away: the next command replaces it.
#!/bin/bash
ls notes.txt
echo "ls finished with $?"
ls photos.txt
echo "ls finished with $?"
exit 3With notes.txt present and no photos.txt, bash check.sh; echo "check.sh exit: $?" prints notes.txt, ls finished with 0, an error from ls, ls finished with 2, then check.sh exit: 3.
exit N stops the script and makes N its exit code. Without exit, a script's code is the code of its last command. true and false are commands that do nothing except exit with 0 and 1.
Challenge
EasyWrite a stock check that reports what grep found and passes its exit code on. grep -q TEXT FILE prints nothing; it exits 0 when it finds the text, 1 when it does not, and 2 when it cannot read the file.
- Open
instock.sh. It takes an item as the first argument and a file as the second. - Run
grep -q "$1" "$2", and on the next line save$?in a variable calledcode. - Print
Search for ITEM finished with code N, where ITEM is the first argument and N is the saved code. - End the script with
exit $code, then save the file.
Try it: run bash instock.sh milk stock.txt; echo "exit $?". It prints:
Search for milk finished with code 0
exit 0Then run bash instock.sh mango stock.txt; echo "exit $?": mango is not in the file, so it prints Search for mango finished with code 1 and exit 1. A missing file gives code 2.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground