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 $?/etc/hosts0ls: cannot access '/nope': No such file or directory201grep 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:
| Code | Usual meaning |
|---|---|
| 0 | success |
| 1 | general failure |
| 2 | wrong usage of the command |
| 126 | found but not executable |
| 127 | command not found |
| 130 | stopped with Ctrl+C |
| 137 | killed (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"; fiweb1 is in the hosts fileWritten 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-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 $?01The spaces inside [[ and ]] are required; [[$env == prod]] is an error.
String tests
| Test | True 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]}"release branchmajor=2 minor=4== 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:
| Test | Meaning |
|---|---|
-eq / -ne | equal / not equal |
-lt / -le | less than / less or equal |
-gt / -ge | greater than / greater or equal |
usage=91[[ $usage -gt 85 ]] && echo "disk usage high: $usage%"For arithmetic comparisons you can also use (( )), which reads more naturally: (( usage > 85 )).
File tests
| Test | True when |
|---|---|
-e path | exists |
-f path | is a regular file |
-d path | is a directory |
-s path | exists and is not empty |
-r / -w / -x path | readable / writable / executable |
a -nt b | file 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"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[ ] 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 && brunsbonly ifasucceeded.a || brunsbonly ifafailed.
mkdir -p /tmp/release && cd /tmp/release && pwdcd /does-not-exist || echo "could not change directory"/tmp/releasebash: cd: /does-not-exist: No such file or directorycould not change directoryA very common pattern stops a script when a step fails:
cd "$build_dir" || exit 1Without || 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 ;;esacEach 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 ;; esac2Real-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"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-gtor(( 10 > 9 )). =for assignment inside a test:[[ $x = 5 ]]compares; it never assigns.- Checking
$?too late: any command, evenecho, replaces it. Save it straight away:cmd; rc=$?. if [ grep ... ]: you do not need brackets around a command. Writeif grep -q ...; then.- Trusting
a && b || cas if/else.
Practice
- Run
systemctl is-active nginxand print its exit code. - Write a one-line
ifthat printsbigwhen a variablenis greater than 100 andsmallotherwise. - Test whether
/var/log/syslogexists and is not empty with-s, and print a message either way. - Use
caseto turn a variablesizewith valuess,m,linto memory limits256Mi,512Mi,1Gi, with an error for anything else. - Use
[[ =~ ]]andBASH_REMATCHto pull the number out ofrelease-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) …;; *) …;; esacKey takeaways
- Every command returns an exit code; 0 is success and anything else is failure.
ifruns 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 1is the simplest safety net.- Use
casewhen one value can match many patterns.