Linux/Unix: Understanding return codes📄 BetterWays.dev wiki page | 🕑 Last updated: Nov 9, 2022
Return codes are used to indicate the success or failure of the function or the script.
Let's make an example script, called
#!/bin/bash if [ "$1" = "OK" ]; then exit 0 fi exit 1
Make it executable:
chmod +x test_code
The script is very simple - we're just taking the first argument passed to the script (
$1) and comparing it to the string "OK". If this is true, we're exiting the script with status 1, otherwise, we're exiting the script with status 0.
Zero status indicates success and every non-zero status indicates failure.
Let's try to execute the script:
We can get the return code of the last command with
The result should be
0 as expected.
For everything else, the return code should be 1:
./test_code NOK echo $?
Shorthand if: && and ||
Instead of writing the whole
if statement each time, we can leverage the shorthand form with
For example, a quicker way to write our script would be:
#!/bin/bash <a href="/1-ok"> $1 = "OK" </a> && exit 0 exit 1
And we can use it like this (
./test_code OK && echo "Success"
./test_code NOK || echo "Failure"
./test_code OK && echo "Success" || echo "Failure" ./test_code NOK && echo "Success" || echo "Failure"
As you can see, this is very convenient, and it's used a lot - both in shell scripting and interactive shell use.
One of the main causes of the fall of the Roman Empire was that, lacking zero, they had no way to indicate successful termination of their C programs.
-- Robert Firth
Ask me anything / Suggestions
If you find this site useful in any way, please consider donating. I'm trying to keep it as clean and fast as possible - there are no ads, no affiliate links, and no analytics/tracking scripts.