Exit Codes
Explore the concept of exit codes in Bash scripting to understand how commands indicate success or failure. Learn standard exit codes, how different programs like grep use them uniquely, and how to set custom exit codes in scripts and functions. This lesson helps you write safer scripts by interpreting and controlling exit statuses effectively.
How Important is this Lesson?
Most bash scripts won’t be completely comprehensible or safely written unless exit codes are understood.
What Is An Exit Code?
After you run a command, function or builtin, a special variable is set that tells you what the result of that command was. If you’re familiar with HTTP codes like 200 or 404, this is a similar concept to that.
To take a simple example, type this in:
When that special variable $? is set to 0 it means that the previous command completed
successfully (line 2). When the special variable $? is set to non-zero (in this case 127 it means that it did not complete successfully.
Standard Exit Codes
There are guidelines for exit codes for those that want to follow standards.
Be aware that not all programs follow these standards (grep is the most common
example of a non-standard program, as you will learn)!
Some key ones are:
0- ‘command successfully run’ (OK)1- Used when there is an error but no specific number reserved to indicate what it was (general error)2