How Linux Exit Codes Help You Write Robust Scripts

4 weeks ago 10

Summary

  • Each Linux bid returns an exit code, with 0 indicating occurrence and non-zero values indicating failure.
  • You tin usage the $? adaptable to entree the exit codification and power programme travel successful scripts.
  • Be cautious of unconventional exit codes that alteration betwixt commands, similar diff and curl.

Every Linux bid volition people mistake messages if it fails, but this accusation is hard to trust on. Your scripts should marque usage of exit codes to beryllium arsenic robust arsenic possible.

What Are Exit Codes?

When you tally a Linux command, it whitethorn fail. Things tin spell incorrect for assorted reasons, but you’ll usually spot a connection explaining why:

A Linux mistake  connection   from the ls bid  speechmaking  "no specified  record  oregon  directory."

The mistake connection you spot appears connected STDERR, a antithetic watercourse from STDOUT, which lets you isolate errors from expected output. As a user, a statement of the mistake should beryllium informative, but scripts and different automated processes request to cognize astir errors much reliably.

An Ubuntu Terminal.

Related

What Are stdin, stdout, and stderr connected Linux?

Mystified by stdin, stdout and stderr? Learn to usage them successful your Linux scripts.

Alongside readable mistake messages, each bid besides returns an exit code. This is simply a fig betwixt 0 and 255 that indicates whether the bid failed oregon succeeded. By default, the exit coe is hidden, but your ammunition provides entree to this worth successful the peculiar variable, $?

The ls bid  returns a 0 exit presumption    connected  occurrence  and a 1 connected  failure.

Note that a 0 worth indicates occurrence and a non-zero worth means failure. You tin cheque this worth connected the bid line, interrogate it successful a script, and usage it to power the travel of your programs.

How Do I Use Exit Codes?

In the illustration above, ls returned a 0 exit codification erstwhile it succeeded and a 1 erstwhile its statement was not a valid file. This mightiness look counterintuitive, and it contradicts emblematic programming languages that dainty 0 arsenic a mendacious worth and 1 arsenic true. However, this setup allows for a single, cosmopolitan occurrence worth and a wide scope of values to correspond antithetic mistake types.

As good arsenic echoing the $? adaptable to manually cheque exit status, you tin usage it with a conditional if statement. If the bid returns a 0 exit status, the connection volition tally the associated past block. Otherwise, if determination is one, it volition tally the other block. For example:

if command; then echo "command succeeded"; else echo "command failed"; fi

You tin usage this conception successful a ammunition script, wherever it’s a small easier to format for readability:

if command
    then echo "command succeeded"
    else echo "command failed"
fi

This is the equivalent of:

command

if [ $? -eq 0 ]
    then echo "command succeeded"
    else echo "command failed"
fi

The longer mentation uses square-bracket syntax to trial the worth of $?, but it’s usually easier to trial the worth directly, arsenic successful the archetypal case. Remember that $? ever represents the exit codification from the past command, truthful beryllium careful. You whitethorn beryllium tempted to output the worth of $? for debugging, e.g.

command

echo "command returned exit code:" $?

if [ $? -eq 0 ]
    then echo "command succeeded"
    else echo "command failed"
fi

But, astatine the constituent of the information check, $? volition person the worth of echo’s exit status, which is astir guaranteed to beryllium 0. To debar this, either trial the bid straight successful the conditional oregon store the worth of $? successful a variable.

Linux laptop showing a terminal model   with a globe signifier   inthe inheritance  and a binary watermark

Related

How to Use Bash If Statements (With 4 Examples)

The if connection is the easiest mode to research conditional execution successful Bash scripts.

What Else Is There to Know About Exit Status?

Exit codes are beauteous simple, pursuing the Unix principle, and this is portion of their power. But determination are immoderate gotchas and exceptional cases you should beryllium alert of.

Exit Codes From Your Shell

Your ammunition volition usage exit codes adjacent erstwhile the bid you benignant doesn’t tally correctly. For example, zsh and bash usage 127 if the bid is not recovered and 126 if the bid is not executable:

A ammunition  league   showing a 127 exit codification  for a non-existent bid  and a 126 codification  for a bid  that cannot beryllium  executed.

Unconventional Exit Codes

Some commands somewhat crook the rules of exit status; they’re truly lone conventions, anyway. For example, diff uses a 0 worth to mean "no differences," a worth of 1 to mean "differences," and a worth of 2 to correspond an error:

Example exit codes from diff.

This tin confuse the meaning of conditionals; for example:

if diff file1 file2; then
    echo these files are the same!
fi

The curl bid is besides a spot unintuitive. You mightiness expect curl to study an HTTP error, similar a 404 for a non-existent URL, arsenic a non-zero presumption code, but it doesn’t:

Exit codes from curl showing that http presumption    is not reflected by default.

You tin usage the -f (--fail) enactment to origin curl to behave differently, returning an exit codification of 22 connected failure:

The curl bid  reporting an HTTP mistake  via an exit codification  with the -f option.

However, beryllium alert that this is not 100% guaranteed and immoderate HTTP errors, including those requiring authentication, volition inactive instrumentality a 0 exit code.

Using Exit Status successful a Command Chain

One of the champion exit presumption shortcuts happens without you adjacent needing to deliberation astir it. Here’s a elemental example:

ls programme && ./program && echo occurrence || echo epic fail

The && and || logical operators fto you tally much than 1 bid based connected the exit presumption of others. They are akin to the corresponding operators successful astir programming languages, but they respect the exit codification convention. The && relation volition tally the bid connected its close lone if the bid connected its near returns a 0 exit status. The || relation volition tally the bid connected its close lone if the bid connected its near fails with a non-zero status.

A concatenation  of commands utilizing logic operators to trial  exit codes.

A precise communal lawsuit occurs erstwhile you physique bundle from scratch, utilizing this recipe:

./configure && marque && marque install

The 3 parts to this bid bash the following:

  • ./configure runs a section publication that inspects your situation and generates a Makefile.
  • marque runs the marque programme and builds the software, utilizing the Makefile.
  • marque instal copies the generated executable to a well-known determination similar /usr/local/bin.

If immoderate portion of this process fails, it volition halt instantly without trying the remainder.

The existent and mendacious Commands

Your Linux strategy includes 2 funny commands: existent and false. Each of these does nothing, but for instrumentality an due exit code: 0 and 1 respectively:

The existent   and mendacious  commands returning 0 and 1 exit codes respectively.

They mightiness not look precise useful, but these commands travel successful useful for investigating and for immoderate ammunition scripting tasks. You tin usage existent successful a portion connection to make an infinite loop:

while true
do
    echo “running until you ^c”
    sleep 10
done

You tin besides usage them unneurotic with logical operators to change bid behavior. For example, you tin temporarily halt a agelong bid concatenation from running:

false && (none || of-these && commands || will-run)

Or you tin unit a bid concatenation to proceed running, adjacent if 1 bid fails:

feline file-that-may-not-exist | true && echo done

Returning an Exit Code From Your Own Scripts

You’ve astir apt utilized the exit bid before, to discontinue your terminal. Technically, it quits your ammunition and this means you tin usage it to halt a ammunition publication too. By default, your scripts volition exit with the aforesaid codification arsenic the past command:

A ammunition  publication   returning its past  command's exit code.

But you tin alteration the exit codification by passing a numerical parameter to the exit command:

exit number

Your publication volition present exit with the presumption codification you supplied, and you tin usage this to pass antithetic mistake conditions from your programme to others.


Once you cognize astir them, exit commands are elemental to use. You whitethorn adjacent usage them without truly reasoning astir it, but erstwhile it comes to scripting, marque definite you’re utilizing exit codes appropriately.

Read Entire Article