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 test_code:

#!/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:

./test_code OK

We can get the return code of the last command with $?:

echo $?

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 && and ||.

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 (and operation):

./test_code OK && echo "Success"

or operation:

./test_code NOK || echo "Failure"

Both operations:

./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


Comments and suggestions

You can use this form to submit a suggestion or a comment.

If you find this site useful, please consider supporting it. Supporters also get access to some extras.