Skip to content
$ lynuxpro
← Bash Scripting

LESSON 4 OF 17 · BEGINNER · 18 MIN

Exit codes and conditionals

HOW IT WORKSExit codes drive every decision

exitgrep -q nginxruns a checkExit code $?0 or 1–255then …code 0 = trueelse …non-zero = falsecmd && nextonly on successcmd || fallbackonly on failure
1/5

Every command exits with a number. 0 means success; anything else is a kind of failure.

$ grep -q nginx /etc/hosts; echo $?
1

Automation is mostly decisions: if the service is down, restart it; if the disk is nearly full, alert; if the build failed, stop. In Bash, every one of those decisions is based on a single number that every command returns when it finishes: its exit code. Once you understand exit codes, if, &&, || and [[ ]] all make sense.

In simple words

  • Exit code: a number every command returns. 0 means success, anything else means failure.
  • if: runs a block of commands only when a command succeeds.
  • [[ ]]: Bash's test command, for comparing strings and numbers and checking whether files exist.
  • && and ||: && runs the next command only on success. || runs it only on failure.
  • case: matches one value against several patterns. Cleaner than many if statements.

Every command returns an exit code

When a command finishes, it returns a number from 0 to 255. Bash stores the last one in $?.

  • 0 means success.
  • Anything else means some kind of failure. The specific number can explain what went wrong.
ls /etc/hostsecho $?ls /nopeecho $?grep -q web1 /etc/hostsecho $?grep -q mysql /etc/hostsecho $?
SHELLbashutf-8 · 8L
/etc/hosts0ls: cannot access '/nope': No such file or directory201
OUTPUTterminalutf-8 · 6L

grep uses 0 for "found", 1 for "not found" and 2 for "an error happened". Many tools document their codes in man tool. Some widely used ones:

CodeUsual meaning
0success
1general failure
2wrong usage of the command
126found but not executable
127command not found
130stopped with Ctrl+C
137killed (often out of memory in containers)

Your own scripts set their exit code with exit N. Without it, a script exits with the code of its last command.

if runs a command and checks its exit code

This is the key idea: if does not evaluate a "true or false expression". It runs a command, and takes the then branch when the exit code is 0.

if grep -q web1 /etc/hosts; then echo "web1 is in the hosts file"; else echo "web1 is missing"; fi
SHELLbashutf-8 · 1L
web1 is in the hosts file
OUTPUTterminalutf-8 · 1L

Written over several lines in a script, which is the normal style:

if grep -q web1 /etc/hosts; then  echo "web1 is in the hosts file"elif grep -q web2 /etc/hosts; then  echo "only web2 found"else  echo "no web hosts"fi
SHELLbashutf-8 · 7L

-q (quiet) tells grep not to print the matching line; we only care about the exit code. You can put any command after if: ping, curl, systemctl is-active, your own script.

To invert a test, put ! in front: if ! grep -q web1 /etc/hosts; then ....

[[ ]]: the test command

To compare values or check files, Bash provides [[ expression ]]. It is a command that exits 0 when the expression is true.

env=prod[[ $env == prod ]]echo $?[[ $env == staging ]]echo $?
SHELLbashutf-8 · 5L
01
OUTPUTterminalutf-8 · 2L

The spaces inside [[ and ]] are required; [[$env == prod]] is an error.

String tests

TestTrue when
[[ $a == $b ]]strings are equal (the right side can be a pattern)
[[ $a != $b ]]strings differ
[[ -z $a ]]string is empty
[[ -n $a ]]string is not empty
[[ $a =~ regex ]]string matches a regular expression
branch=release/2.4[[ $branch == release/* ]] && echo "release branch"version=2.4.1[[ $version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] && echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}"
SHELLbashutf-8 · 4L
release branchmajor=2 minor=4
OUTPUTterminalutf-8 · 2L

== with an unquoted right side does pattern matching (*, ?). Quote the right side for an exact comparison: [[ $a == "$b" ]].

Number tests

Bash compares numbers with letters, because < and > compare strings alphabetically:

TestMeaning
-eq / -neequal / not equal
-lt / -leless than / less or equal
-gt / -gegreater than / greater or equal
usage=91[[ $usage -gt 85 ]] && echo "disk usage high: $usage%"
SHELLbashutf-8 · 2L

For arithmetic comparisons you can also use (( )), which reads more naturally: (( usage > 85 )).

File tests

TestTrue when
-e pathexists
-f pathis a regular file
-d pathis a directory
-s pathexists and is not empty
-r / -w / -x pathreadable / writable / executable
a -nt bfile a is newer than b
[[ -f /etc/hosts ]] && echo "hosts file exists"[[ -d /var/log/nginx ]] && echo "nginx log dir exists"[[ -x /etc/hosts ]] || echo "hosts is not executable"
SHELLbashutf-8 · 3L

Combining tests

Inside [[ ]] use &&, ||, ! and parentheses:

env=prod; replicas=1if [[ $env == prod && $replicas -lt 2 ]]; then echo "prod should run at least 2 replicas"; fi
SHELLbashutf-8 · 2L

[ ] and test (the older form)

You will see [ $a = $b ] in older scripts and in POSIX sh. It is the same idea but stricter: variables must be quoted, == is not portable (use =), and && must go outside: [ "$a" = x ] && [ "$b" = y ]. In Bash scripts, prefer [[ ]]. You will learn when [ ] is required in the portable shell lesson.

&& and ||: short conditionals

For simple cases, && and || are a compact if:

  • a && b runs b only if a succeeded.
  • a || b runs b only if a failed.
mkdir -p /tmp/release && cd /tmp/release && pwdcd /does-not-exist || echo "could not change directory"
SHELLbashutf-8 · 2L
/tmp/releasebash: cd: /does-not-exist: No such file or directorycould not change directory
OUTPUTterminalutf-8 · 3L

A very common pattern stops a script when a step fails:

cd "$build_dir" || exit 1
SHELLbashutf-8 · 1L

Without || exit 1, a failed cd leaves the script in the wrong folder, and the following rm -rf * deletes the wrong files.

Be careful combining both: a && b || c is not an if/else. If b itself fails, c also runs. Use a real if when that matters.

case: matching one value against many patterns

When you compare one variable against several values, case is cleaner than a chain of elif:

case "$env" in  prod|production) replicas=4 ;;  staging)         replicas=2 ;;  dev*)            replicas=1 ;;  *)               echo "unknown env: $env" >&2; exit 2 ;;esac
SHELLbashutf-8 · 6L

Each pattern ends with ), each branch ends with ;;, | means "or", and *) catches everything else. Try it in one line:

env=staging; case "$env" in prod) echo 4 ;; staging) echo 2 ;; *) echo 1 ;; esac
SHELLbashutf-8 · 1L
2
OUTPUTterminalutf-8 · 1L

Real-world scenario: a pre-deploy gate

Before a deploy, a pipeline step checks that the inputs make sense and that the target is healthy. Each check is just a command and its exit code:

#!/usr/bin/env bashapp=${1:?usage: $0 APP ENV VERSION}env=${2:?usage: $0 APP ENV VERSION}version=${3:?usage: $0 APP ENV VERSION} if [[ ! $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then  echo "version must look like 1.2.3, got '$version'" >&2  exit 2fi case "$env" in  staging|prod) ;;  *) echo "env must be staging or prod" >&2; exit 2 ;;esac if ! curl -fsS "https://$env.example.com/health" > /dev/null; then  echo "$env is unhealthy, refusing to deploy" >&2  exit 1fi echo "All checks passed: deploying $app $version to $env"
SHELLbashutf-8 · 21L

curl -f makes curl return a non-zero exit code on HTTP errors like 500, so the if ! catches an unhealthy service. Every line here is something you have now learned.

Common mistakes

  • Missing spaces: [[$x==1]] must be [[ $x == 1 ]].
  • Using > for numbers: [[ 10 > 9 ]] is false, because it compares text. Use -gt or (( 10 > 9 )).
  • = for assignment inside a test: [[ $x = 5 ]] compares; it never assigns.
  • Checking $? too late: any command, even echo, replaces it. Save it straight away: cmd; rc=$?.
  • if [ grep ... ]: you do not need brackets around a command. Write if grep -q ...; then.
  • Trusting a && b || c as if/else.

Practice

  1. Run systemctl is-active nginx and print its exit code.
  2. Write a one-line if that prints big when a variable n is greater than 100 and small otherwise.
  3. Test whether /var/log/syslog exists and is not empty with -s, and print a message either way.
  4. Use case to turn a variable size with values s, m, l into memory limits 256Mi, 512Mi, 1Gi, with an error for anything else.
  5. Use [[ =~ ]] and BASH_REMATCH to pull the number out of release-42.

Cheat sheet

$?                         exit code of the last command (0 = success)exit N                     end the script with code Nif cmd; then …; elif …; else …; fiif ! cmd; then …           invert[[ $a == "$b" ]]           exact string compare[[ $a == pat* ]]           pattern match[[ $a =~ ^re$ ]]           regex, groups in BASH_REMATCH[[ -z $a ]]  [[ -n $a ]]   empty / not empty-eq -ne -lt -le -gt -ge    numbers(( n > 5 ))                arithmetic test-e -f -d -s -x             file testsa && b    a || b           run b on success / failurecmd || exit 1              stop on failurecase $x in a|b) …;; *) …;; esac
OUTPUTterminalutf-8 · 14L

Key takeaways

  • Every command returns an exit code; 0 is success and anything else is failure.
  • if runs a command and branches on its exit code; [[ ]] is just a command that tests values.
  • Compare numbers with -gt, -lt (or (( ))), strings with ==, and files with -f, -d, -s.
  • && and || chain commands on success or failure; cmd || exit 1 is the simplest safety net.
  • Use case when one value can match many patterns.