Skip to content
Visual explainer 5h to learn 5 steps

Bash scripting essentials

Write Bash scripts with variables, loops, conditionals and exit codes.

By Invicly Tech, , in Full DevOps with Python. About 10 minutes to read.

Topic 3 of 34

In short

Bash scripts glue Linux commands together into repeatable tasks. Quoting variables, checking exit codes and using strict mode make scripts fail loudly instead of silently doing damage.

Explained simply

A Bash script is a text file full of commands you would otherwise type by hand. Bash runs them top to bottom. If you have ever pasted the same five commands into a terminal twice, that is a script waiting to be written.

Bash is a bit unusual because it changes your command before running it. It swaps $NAME for its value, expands *.log into a list of file names, and splits text on spaces. Most Bash bugs come from this hidden rewriting, which is why quoting matters so much.

Scripts make decisions by looking at exit codes. Every command quietly reports a number when it ends: 0 means it worked, anything else means it failed. if, &&, || and set -e all read that number. Think of it as a thumbs up or thumbs down after every line.

In DevOps, Bash is the glue for small jobs: setting up a server, wrapping a deploy, rotating backups, running steps in CI. When a script grows past about 100 lines or needs real data handling, that is usually the moment to switch to Python.

Press Play on a diagram to walk through it one step at a time.

MapAnatomy of a safe script
backup.sh
  • Header
    • #!/usr/bin/env bash
    • set -euo pipefail
  • Variables
    • SRC="$1"
    • Always quote "$VAR"
    • ${2:-default} fallbacks
  • Functions
    • log() and die() helpers
    • One job per function
  • Control flow
    • if [[ -d $dir ]]
    • case for options
    • for f in *.log
  • Exit codes
    • 0 means success
    • Non-zero means failure
    • $? holds the last code
FlowHow Bash rewrites one line
  1. 1
    Brace expansion

    {a,b}.txt becomes a.txt b.txt

  2. 2
    Tilde and variables

    ~ and $VAR get their values

  3. 3
    Command substitution

    $(date +%F) becomes 2026-11-09

  4. 4
    Word splitting

    Unquoted results are cut on spaces

  5. 5
    Globbing

    *.log becomes matching file names

  6. 6
    Run

    The final words become the command

CompareThree kinds of test
[ ]
  • Works in any sh
  • Quote every variable
  • Use -a and -o carefully
  • Example: [ -f "$f" ]
[[ ]]
  • Bash only
  • No word splitting inside
  • Patterns and =~ regex
  • Example: [[ $f == *.log ]]
(( ))
  • Whole-number arithmetic
  • Normal < > == signs
  • Variables without $
  • Example: (( n > 5 ))

In depth

What Bash does to a line before running it

Bash processes each line in stages. First it expands braces, so {a,b}.txt becomes a.txt b.txt. Then it replaces ~ with your home folder, $VAR with its value, $(cmd) with the command's output and $((1+2)) with 3. Next comes word splitting: unquoted results are cut on spaces, tabs and newlines. Finally globbing turns *.log into matching file names.

Quotes switch some stages off. Double quotes keep variables working but stop word splitting and globbing. Single quotes stop everything, so '$HOME' stays as the literal text $HOME.

  • "$file" stays one word, even with spaces in it
  • '$HOME' is literal text
  • set -x prints each line after expansion, great for debugging

Tests: [ ], [[ ]] and (( ))

[ ] is the old, portable test command and needs careful quoting. [[ ]] is Bash's improved version: it doesn't word-split variables, supports && and || inside, and can match patterns like [[ $f == *.log ]] or regular expressions with =~. (( )) is for arithmetic, so (( count > 5 )) reads naturally.

Use [[ ]] in Bash scripts and [ ] only when the script must run under plain sh. Common checks: -f for a regular file, -d for a directory, -z for an empty string, -n for a non-empty one.

Cleaning up with trap

Scripts often create temporary files or start background jobs. If the script fails halfway, those are left behind. trap runs a command when the script exits, for any reason, including errors under set -e and Ctrl+C.

The usual pattern is: create a temp folder with mktemp -d, then trap 'rm -rf "$tmp"' EXIT. Now the folder disappears whether the script succeeds or crashes. You can also trap ERR to print the line number that failed, which makes CI logs much easier to read.

  • tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT
  • trap 'echo "failed at line $LINENO"' ERR
  • Never build temp names by hand like /tmp/myfile
FlowCleanup that always runs
  1. 1
    tmp=$(mktemp -d)

    Safe, unique temp folder

  2. 2
    trap ... EXIT

    Register the cleanup command

  3. 3
    Script does its work
  4. 4
    Script exits

    Success, error under set -e, or Ctrl+C

  5. 5
    Trap runs

    rm -rf "$tmp" removes the folder

Reading input safely

for f in $(ls) breaks on file names with spaces. Prefer globs: for f in /var/log/*.log; do ...; done. To process command output line by line, use while IFS= read -r line; do ...; done < file. IFS= keeps leading spaces and -r keeps backslashes as they are.

Be careful with pipes: in cmd | while read ...; the loop runs in a subshell, so variables set inside vanish afterwards. Feed the loop with process substitution instead: while read -r x; do ...; done < <(cmd). Finally, run shellcheck on every script; it catches most of these traps automatically.

CompareWhere a while-read loop runs
cmd | while read -r x
  • Loop runs in a subshell
  • Variables set inside vanish
  • A counter reads 0 after the loop
while read -r x ... < <(cmd)
  • Loop runs in the current shell
  • Variables keep their values
  • A counter is correct after the loop

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Use variables, quoting and arguments~1h
  2. 2
    Write if tests and case statements~1h
  3. 3
    Loop over files and command output~1h
  4. 4
    Check exit codes and use set -euo pipefail~1h
  5. 5
    Write a backup script with functions~1h

Key points

  • set -euo pipefail stops on errors, unset variables and failed pipeline stages.
  • Quote every variable expansion so spaces in file names do not break commands.
  • Every command returns an exit code; 0 is success and anything else is failure.
  • Use functions and clear names so a script still reads well months later.

Key terms

Tap a card to flip it. 0/5 known

Examples

bash
#!/usr/bin/env bash
set -euo pipefail

SRC="${1:?usage: backup.sh SRC [DEST]}"
DEST="${2:-/backups}"

log() { echo "[$(date +%T)] $*"; }

[[ -d "$SRC" ]] || { log "No such dir: $SRC"; exit 1; }
mkdir -p "$DEST"
file="$DEST/$(basename "$SRC")-$(date +%F).tar.gz"
tar -czf "$file" "$SRC"
log "Saved $file"

A small backup script with strict mode and argument checks.

Delete logs older than 7 days, safely

Goal: free disk space in a log folder passed as an argument. Step 1: strict mode, so errors stop the script. Step 2: refuse to run without a real directory. Step 3: list what would be deleted first, so a person can review it in dry-run mode. Step 4: delete only when DRY_RUN=0. Using find -print0 and xargs -0 keeps odd file names safe.

bash
#!/usr/bin/env bash
set -euo pipefail
dir="${1:?usage: clean-logs.sh DIR}"
[[ -d "$dir" ]] || { echo "not a directory: $dir" >&2; exit 2; }

echo "Old logs in $dir:"
find "$dir" -name '*.log' -mtime +7 -print

if [[ "${DRY_RUN:-1}" == 0 ]]; then
  find "$dir" -name '*.log' -mtime +7 -print0 | xargs -0 -r rm -f
  echo "deleted"
else
  echo "dry run; set DRY_RUN=0 to delete"
fi

Check the health of several servers

Goal: call /health on each host and fail the script if any is down, so CI or cron can alert. Step 1: keep the hosts in an array. Step 2: loop and call curl with a short timeout; -f makes curl fail on HTTP errors. Step 3: count failures instead of stopping at the first one. Step 4: exit 1 if anything failed. Note we don't use set -e here, because we want to keep going after a failed host.

bash
#!/usr/bin/env bash
set -uo pipefail
hosts=(api1.example.com api2.example.com api3.example.com)
failed=0
for h in "${hosts[@]}"; do
  if curl -fsS --max-time 5 "https://$h/health" >/dev/null; then
    echo "OK   $h"
  else
    echo "DOWN $h"; failed=$((failed + 1))
  fi
done
echo "$failed host(s) down"
(( failed == 0 ))

Quick reference

  • "$var" for values, '...' for literal text, "${arr[@]}" for every array item
  • ${VAR:-default} uses a default; ${VAR:?message} stops if VAR is unset
  • bash -n script.sh checks syntax; bash -x script.sh traces each line
  • shellcheck script.sh finds quoting bugs and common mistakes
  • tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT cleans up on any exit
  • while IFS= read -r line; do ...; done < file reads lines safely
  • $? is the last exit code; $# is the number of arguments

Common mistakes

  • Unquoted $file breaks on names with spaces and can delete the wrong things.
  • Piping into another command hides the first command's failure without pipefail.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A variable file holds "my report.txt". What does rm $file (unquoted) try to delete?

Question 2

2What does echo '$HOME' print?

Question 3

3Why does count stay 0 after: cat list | while read x; do count=$((count+1)); done?

Question 4

4Which line removes a temp folder even if the script fails halfway?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write greet.sh that takes a name as the first argument, prints Hello, NAME, and exits with code 2 and a usage message if no name is given.

  2. Exercise 2medium

    Write a script that counts how many lines in /var/log/syslog (or any log) contain ERROR, WARN and INFO, and prints the three counts.

  3. Exercise 3hard

    Write backup.sh SRC DEST that creates a dated tar.gz of SRC in DEST, keeps only the 5 newest backups, uses a temp file that is cleaned up on failure, and only moves the archive into place when tar succeeded.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I write #!/bin/bash or #!/usr/bin/env bash?
#!/usr/bin/env bash finds bash wherever it is on the PATH, which works on more systems, including macOS with a newer Homebrew Bash. On standard Linux servers both work.
When should I switch from Bash to Python?
Switch when you need data structures, JSON parsing, error handling with retries, or the script passes about 100 lines. Bash is best for short glue around other commands.
Why does my script work in my terminal but not in cron?
cron uses a tiny PATH and no shell profile, so commands and variables you rely on are missing. Use absolute paths or set PATH at the top of the script.

Go deeper

ShareXLinkedInWhatsApp