Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Pro

Production-ready scripts

A script you run once on your laptop can be rough. A script that deploys software, runs from cron, or is used by your whole team needs more: clear usage, options, safety checks, logs, a dry-run mode, and predictable behaviour when things go wrong. This lesson builds one step by step and finishes with a template you can reuse.

A script template

tool.sh
#!/usr/bin/env bash
#
# tool.sh: sync a folder to a backup location.
#
# Usage: tool.sh [-n] [-v] [-k N] SOURCE DEST
#
set -euo pipefail
IFS=$'\n\t'

readonly SCRIPT_NAME=${0##*/}
readonly VERSION="1.2.0"

# ---------- defaults (can be overridden by options or environment) ----------
DRY_RUN=false
VERBOSE=false
KEEP=${KEEP:-5}

# ---------- helpers ----------
log()   { local IFS=' '; printf '%s [%s] %s\n' "$(date -u '+%H:%M:%S')" "$1" "${*:2}" >&2; }
info()  { log INFO "$@"; }
debug() { if [[ $VERBOSE == true ]]; then log DEBUG "$@"; fi; }
die()   { log ERROR "$@"; exit 1; }

# Run a command, or only print it in dry-run mode.
run() {
  local IFS=' '      # join "$*" with spaces in messages
  if [[ $DRY_RUN == true ]]; then
    info "dry-run: $*"
  else
    debug "running: $*"
    "$@"
  fi
}

usage() {
  cat <<EOF
Usage: $SCRIPT_NAME [options] SOURCE DEST

Copy SOURCE into a dated folder inside DEST and keep the newest N copies.

Options:
  -n        dry run: show what would happen, change nothing
  -v        verbose output
  -k N      number of copies to keep (default: $KEEP)
  -h        show this help
  -V        show the version
EOF
}

# ---------- option parsing ----------
while getopts ":nvk:hV" opt; do
  case $opt in
    n) DRY_RUN=true ;;
    v) VERBOSE=true ;;
    k) KEEP=$OPTARG ;;
    h) usage; exit 0 ;;
    V) echo "$SCRIPT_NAME $VERSION"; exit 0 ;;
    :) die "option -$OPTARG needs a value" ;;
    \?) die "unknown option -$OPTARG (see -h)" ;;
  esac
done
shift $(( OPTIND - 1 ))

# ---------- validation: check everything before changing anything ----------
(( $# == 2 )) || { usage >&2; exit 2; }
src=$1
dest=$2
[[ -d $src ]] || die "source '$src' is not a folder"
[[ $KEEP =~ ^[1-9][0-9]*$ ]] || die "-k needs a positive number, got '$KEEP'"
command -v rsync > /dev/null || debug "rsync not found, using cp"

# ---------- the work ----------
main() {
  local stamp target
  stamp=$(date -u +%Y%m%d-%H%M%S)
  target="$dest/$(basename "$src")-$stamp"

  info "copying $src → $target"
  run mkdir -p "$dest"
  run cp -a "$src" "$target"

  local old
  mapfile -t old < <(find "$dest" -maxdepth 1 -mindepth 1 -type d -name "$(basename "$src")-*" | sort -r | tail -n +$(( KEEP + 1 )))
  for dir in "${old[@]}"; do
    run rm -rf -- "$dir"
    [[ $DRY_RUN == true ]] || info "removed old copy ${dir##*/}"
  done
  info "done"
}

main

That's long, but every section is there for a reason. Let's try it:

bash
chmod +x tool.sh
./tool.sh -h
echo "---"
./tool.sh -V
./tool.sh; echo "exit $?"
./tool.sh -x a b 2>&1 | cut -c10-; echo "exit ${PIPESTATUS[0]}"
./tool.sh -k zero a b 2>&1 | cut -c10-
Output
Usage: tool.sh [options] SOURCE DEST

Copy SOURCE into a dated folder inside DEST and keep the newest N copies.

Options:
  -n        dry run: show what would happen, change nothing
  -v        verbose output
  -k N      number of copies to keep (default: 5)
  -h        show this help
  -V        show the version
---
tool.sh 1.2.0
Usage: tool.sh [options] SOURCE DEST

Copy SOURCE into a dated folder inside DEST and keep the newest N copies.

Options:
  -n        dry run: show what would happen, change nothing
  -v        verbose output
  -k N      number of copies to keep (default: 5)
  -h        show this help
  -V        show the version
exit 2
[ERROR] unknown option -x (see -h)
exit 1
[ERROR] source 'a' is not a folder

(cut -c10- hides the time at the start of each log line.)

Dry runs

Anything destructive should offer a dry run: show what would happen without doing it. The run helper makes that free: every command that changes something goes through it.

bash
mkdir -p site/css && echo "<h1>hi</h1>" > site/index.html
for d in 20251101 20251102 20251103; do mkdir -p "backups/site-$d-000000"; done
./tool.sh -n -k 2 site backups 2>&1 | cut -c10- | sed -E 's/2026[0-9]{4}-[0-9]{6}/NOW/'
echo "--- nothing changed:"
ls backups
Output
[INFO] copying site → backups/site-NOW
[INFO] dry-run: mkdir -p backups
[INFO] dry-run: cp -a site backups/site-NOW
[INFO] dry-run: rm -rf -- backups/site-20251101-000000
[INFO] done
--- nothing changed:
site-20251101-000000  site-20251102-000000  site-20251103-000000

Then the real run, with -v for extra detail:

bash
./tool.sh -v -k 2 site backups 2>&1 | cut -c10- | sed -E 's/2026[0-9]{4}-[0-9]{6}/NOW/'
echo "--- after:"
ls -1 backups | sed -E 's/2026[0-9]{4}-[0-9]{6}$/NOW/'
Output
[DEBUG] rsync not found, using cp
[INFO] copying site → backups/site-NOW
[DEBUG] running: mkdir -p backups
[DEBUG] running: cp -a site backups/site-NOW
[DEBUG] running: rm -rf -- backups/site-20251102-000000
[INFO] removed old copy site-20251102-000000
[DEBUG] running: rm -rf -- backups/site-20251101-000000
[INFO] removed old copy site-20251101-000000
[INFO] done
--- after:
site-20251103-000000
site-NOW

The pieces, explained

getopts for options

getopts is Bash's built-in option parser. In ":nvk:hV":

  • each letter is an allowed option;
  • a : after a letter (k:) means it takes a value, delivered in $OPTARG;
  • the : at the start lets you print your own error messages (cases : and \?).

After the loop, shift $(( OPTIND - 1 )) removes the options, leaving only the positional arguments. getopts handles short options (-n -v and -nv). For long options like --dry-run, use a while (( $# )); do case $1 in … loop instead.

Exit codes that mean something

Code Convention
0 Success
1 General error
2 Wrong usage (bad options or arguments)
126 / 127 Not executable / command not found (set by the shell)
130 Stopped with Ctrl + C (128 + signal 2)

IFS=$'\n\t'

Setting IFS to newline and tab means unquoted expansions split only on those, not on spaces: a second safety net for file names with spaces. You should still quote everything. One side effect: "$*" joins words with the first character of IFS, now a newline, which is why log and run set local IFS=' ' before building their messages.

Logs on stderr, data on stdout

Every message goes through log to stderr, with a time and a level. Anything a caller might want to capture (like a list of files) goes to stdout. Then ./tool.sh … > files.txt and ./tool.sh … 2> tool.log both do the right thing.

Making scripts safe to run twice

Good automation is idempotent: running it again changes nothing if the work is already done. Use commands that are naturally safe to repeat:

Instead of Use
mkdir dir mkdir -p dir
ln -s target link ln -sfn target link
echo "line" >> config grep -qxF "line" config || echo "line" >> config
useradd deploy id deploy &>/dev/null || useradd deploy
rm file rm -f file
bash
add_line() { grep -qxF "$1" "$2" 2>/dev/null || echo "$1" >> "$2"; }
add_line 'export EDITOR=vim' demo.bashrc
add_line 'export EDITOR=vim' demo.bashrc
add_line 'alias ll="ls -l"' demo.bashrc
cat demo.bashrc
Output
export EDITOR=vim
alias ll="ls -l"

Locking, timeouts and signals

job.sh
#!/usr/bin/env bash
set -euo pipefail
exec 9> /tmp/job.lock                       # open file descriptor 9 on the lock file
flock -n 9 || { echo "already running" >&2; exit 1; }
trap 'echo "stopping cleanly" >&2; exit 130' INT TERM
echo "working (pid $$)…" | sed 's/[0-9]\+/PID/'
timeout 2 sleep 10 || echo "sleep timed out after 2s (exit $?)"
bash
bash job.sh
Output
working (pid PID)…
sleep timed out after 2s (exit 124)
  • exec 9> file + flock -n 9 locks for the whole lifetime of the script.
  • timeout 2 cmd kills a command that takes too long. Its exit code is 124.
  • The INT TERM trap turns Ctrl + C or kill into a clean, logged exit.

Configuration: arguments, environment, files

A good order of precedence is command-line option > environment variable > config file > default:

bash
cat > settings.conf <<'EOF'
PORT=8000
WORKERS=2
EOF
load() {
  local port=8080 workers=4                       # defaults
  # shellcheck disable=SC1091
  [[ -f settings.conf ]] && source settings.conf   # config file
  port=${APP_PORT:-${PORT:-$port}}                 # environment beats the file
  workers=${WORKERS:-$workers}
  echo "port=$port workers=$workers"
}
load
APP_PORT=9000 load
Output
port=8000 workers=2
port=9000 workers=2

Never put passwords or tokens in a script. Read them from the environment (${DB_PASSWORD:?}), a file with 600 permissions, or a secret manager.

Portability checklist

  • #!/usr/bin/env bash, and say which Bash version you need (4+ for associative arrays and mapfile).
  • GNU (Linux) and BSD (macOS) tools differ: sed -i, date -d, readlink -f, grep -P. Test on the system the script runs on, or check uname.
  • Don't parse ls output; use globs or find -print0 | xargs -0.
  • Use command -v (not which) to check for programs.
  • Run ShellCheck in CI: shellcheck scripts/*.sh.
bash
shellcheck tool.sh job.sh && echo "ShellCheck: no problems found"
Output
ShellCheck: no problems found

When not to use Bash

Bash is perfect for gluing commands together. Switch to Python (or Go) when the script needs real data structures, JSON or HTTP APIs beyond jq and curl, careful error handling around many steps, unit tests, or grows past a few hundred lines. A good rule: if you're fighting the language more than the problem, it's time to move.

Practice

  1. Copy the template and turn one of your earlier scripts into a "production" version with -h, -n and -v.
  2. Add a long option --dry-run using a while (( $# )); do case $1 in … loop.
  3. Make a setup script idempotent: run it three times and check nothing is duplicated.
  4. Add a GitHub Actions step (or a git pre-commit hook) that runs shellcheck on every .sh file.
✎ Check your understanding

1.What is a "dry run"?

2.In getopts ":ab:c", which option takes a value?

3.What does "idempotent" mean for a script?

4.Where should a script print log messages?

← Cron and scheduling