Skip to content

Shell Scripting & Text Processing: Bash, Pipes, grep, sed, awk, jq, Safe Scripts ​

"Shell should only be used for small utilities or simple wrapper scripts." — Google, Shell Style Guide ("When to use Shell")

Summary: A shell script is glue: it starts programs, wires their standard streams together with pipes and decides what to do from their exit statuses. It is excellent at that and treacherous at everything else, because every value is a string that gets split, globbed and re-parsed unless you quote it, and every failure is silently ignored unless you ask for it. This chapter teaches the language precisely, the text tools (grep, sed, awk, cut, sort, uniq, tr, wc, jq, yq) that make pipelines powerful, and the safe-script skeleton (strict mode, traps, temp files, locks, dry-run, logging, tests) that makes a script fit for cron, CI and deploys. Focus: bash versus sh versus zsh and POSIX sh, the shebang, exit status and set -euo pipefail (with its traps), quoting, word splitting, globbing and IFS, variables and parameter expansion with default values, arrays, functions, conditionals with test, [ ] and [[ ]], loops, here-docs, command substitution, pipes and redirection (stdin, stdout, stderr, 2>&1, tee), find and xargs, grep with BRE versus ERE, sed substitutions and in-place edits, awk fields and aggregations, cut sort uniq tr wc, jq filters and yq, curl in scripts, trap and cleanup, mktemp, locks with flock and with mkdir, idempotent scripts, dry-run flags, logging, argument parsing with getopts, environment variables, .env files and secrets, shellcheck, shfmt, Bats, cron-safe scripts, macOS BSD versus GNU portability, when to switch to Go or Python, a deploy script, log-analysis one-liners, Laravel artisan in scripts and Go binary wrappers. Learning goal: Write a 60-line script that survives spaces in filenames, a failing step, a second concurrent run, Ctrl-C and cron's minimal environment; read any one-liner and say what it does and where it breaks; run the same text job in awk and in Go and know which to keep; and recognise the moment a script should become a program.

This chapter belongs to the Linux & Tooling group. The machine under the shell (processes, users and permissions, filesystems, packages, systemd) is Linux for Developers; a script becomes a real pipeline job in CI/CD Pipelines; when the job is "configure fifty servers" the answer is usually Configuration Management with Ansible, not a longer script. On the Go side, flags and environment variables are in CLI Flags, Subcommands, Environment Variables & Logging and signals and os/exec in OS Processes, Signals & Graceful Shutdown; bytes, UTF-8 and why tr and cut misbehave on multibyte text are in Bits, Bytes & Text Encoding.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why shell exists and why it bitesWhy it exists
Bourne, POSIX, bash, zsh, macOS and bash 3.2Where it comes from
bash vs sh vs zsh, POSIX sh, shebangShells and the shebang
exit status, set -euo pipefailExit status and strict mode
IFS, quoting, word splitting, globbingQuoting, word splitting, globbing
variables and parameter expansion, default values, arraysVariables and parameter expansion
functions, conditionals, test and [[ ]], loopsControl flow
here-docs, command substitutionHere-docs and command substitution
pipes and redirection, stdin stdout stderr, 2>&1, teePipes and redirection
find, xargsfind and xargs
grep and regular expressions, ERE vs BREgrep
sed substitutions and in-place editssed
awk fields and aggregationsawk
cut sort uniq tr wcThe small tools
jq filters, yqjq and yq
curl in scriptscurl in scripts
trap and cleanup, temp files mktemptrap, cleanup and mktemp
locks (flock)Locks
idempotent scripts, dry-run flags, logging in scriptsIdempotence, dry-run, logging
argument parsing getoptsgetopts
environment variables, .env files and secretsEnvironment and secrets
shellcheck, shfmt, bats testingLint, format, test
cron-safe scriptscron-safe scripts
portability (macOS BSD tools vs GNU)Portability
when to switch to Go or PythonWhen to leave shell
Build graph of a pipeline, expansion order, knobs, error messagesMechanics
Go twin of the awk job; Go binary wrappersGo
Laravel artisan in scriptsLaravel
writing a deploy script, log analysis one-linersSolving the classic problems
Which tool, which shell, which lockChoosing
One laptop to a fleetIn architecture
Commands with real outputLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The four things every script must get right.

ConcernThe default (dangerous) behaviourThe fixCost of the fix
FailureA failing command is ignored; the script goes on and reports successset -euo pipefail, then check the cases it does not coverYou must guard commands whose failure is normal (grep -q, diff)
ValuesAn unquoted $x is split on whitespace and then globbedQuote every expansion: "$x", "$@", "${arr[@]}"Looks noisy; shellcheck SC2086 finds every miss
CleanupTemp files and half-written output survive a crashmktemp -d plus trap cleanup EXIT; write to a temp name, then mvOne trap function per script
ConcurrencyTwo cron runs overlap and corrupt shared stateA lock: flock -n on Linux, mkdir anywhereDecide what "busy" means: skip (0) or alarm (non-zero)

Which text tool for which job.

JobToolOne-linerMental model
Find linesgrep -E / grep -Fgrep -E ' 5[0-9]{2} ' access.txtFilter: line in, line out or nothing
Change part of a linesedsed -E 's/foo([0-9]+)/bar\1/g'Stream editor: one regex substitution per line
Columns, sums, groupsawkawk '{n[$1]++} END{for(k in n) print k, n[k]}'Per-line program with variables and an END block
Fixed columns / countingcut, sort, uniq -c, tr, wccut -d' ' -f1 f | sort | uniq -c | sort -rnSmall single-purpose filters
JSONjqjq -r '.orders[].id' o.jsonA pure-functional filter language
YAMLyq (mikefarah v4)yq '.service.replicas' c.yamljq-style syntax over YAML
Find filesfind + xargs -0find . -name '*.log' -print0 | xargs -0 gzipTree walk with NUL-safe hand-off

Exit statuses worth knowing.

StatusMeaningWhere it comes from
0SuccessConvention, POSIX
1Generic failure; also grep found no matchProgram-defined
2Usage error; also test on a bad operand; grep errorConvention
126Found but not executableThe shell
127Command not foundThe shell
128+NKilled by signal N: 130 = Ctrl-C (SIGINT), 137 = SIGKILL, 141 = SIGPIPE, 143 = SIGTERMThe shell, for a child that died from a signal
22 / 7 / 28curl: HTTP error with --fail / connection refused / timeoutcurl
1 / 4jq -e: 1 when the last output was false or null; 4 when no output was producedjq

What differs between shells you will meet.

FeaturePOSIX sh (dash, BusyBox ash)bashzshNotes
ArraysNoYes (0-based); associative arrays from bash 4Yes (1-based)The lab runs the same program in each
[[ ]]NoYesYesNot POSIX
Unquoted $var splits on whitespaceYesYesNo (by default)zsh is the odd one out
localNot in the standard (all common shells have it)YesYesksh93 lacks it
pipefailIn POSIX.1-2024 (Issue 8)YesYesdash support is recent; check your version
macOS /bin/sh and /bin/bashbash 3.2 in POSIX mode3.2.57zsh 5.9 is the default login shellbash 5 only via Homebrew
grep ERROR app.log | sort | uniq -c (each stage is its own process)grepfd 0 fd 1 fd 2sortfd 0 fd 1 fd 2uniq -cfd 0 fd 1 fd 2pipe (stdout)pipe (stdout)terminal: every stderr (fd 2) lands here and is NOT piped; the last stdout does tooRedirections are applied left to rightcmd > out.log 2>&11. fd 1 now points at out.log2. fd 2 becomes a copy of fd 1 (out.log)stdout and stderr both in the filecmd 2>&1 > out.log1. fd 2 becomes a copy of fd 1 (the terminal)2. fd 1 now points at out.logstderr still on the terminal, stdout in the file

Why it exists ​

Every Unix command already does one thing and writes text to a stream. The shell is the one program whose whole job is to start those commands, connect their streams and branch on their exit statuses. The alternative to a shell script for "rotate these logs, compress them, tell me if anything failed" is a program with a build step, a runtime and a dependency list; for a ten-line job that is far more machinery than the job.

Shell scriptReal program (Go, Python)
Zero build, runs anywhere a shell exists, edited in place on a serverCompiled or packaged, tested in CI, versioned
Everything is a string; types, errors and structure are conventionsReal types, error values, data structures
Pipelines compose existing tools for freeLibraries replace the tools; you own the glue
Failure handling is opt-in and easy to get wrongFailure handling is explicit in every call
Unit-testing is awkward (Bats, stubs on PATH)go test, pytest
Concurrency is &, wait and xargs -PGoroutines, async, worker pools

An everyday picture. A shell script is a kitchen assistant who follows the recipe literally. Say "take the bowl from the shelf" and mean the one named "big bowl", and the assistant will bring two bowls, one called "big" and one called "bowl". Quoting is how you say "the thing named exactly big bowl".

Three common misunderstandings, up front ​

  1. "set -e makes my script safe." It does not fire inside if conditions, on the left of && and ||, in pipelines except the last stage (without pipefail), or inside a function that is called from one of those. It is a safety net with holes, not a guarantee (see exit status).
  2. "Quotes are for strings with spaces." Quotes are for every expansion: they switch off word splitting and globbing, so the value arrives as one argument whatever it contains. A variable that "never has spaces" will have one, in production, on a Friday.
  3. "Shell is just a worse Python." It is a different tool: when the job is "start programs and connect them", a pipeline is shorter, faster to write and often faster to run than the equivalent Python. The failure is using it past its limit (data structures, retries, parsing, concurrency), not using it at all.

Where it comes from ​

YearEventWhy it matters here
1971-73Thompson shell, then pipes added to UnixThe pipe | is the idea the whole chapter rests on
1977Bourne shell (sh)Defines the script syntax: if/fi, case/esac, $1, "$@", here-docs
1989-91GNU bash 1.x, written for the GNU project as a free Bourne-compatible shellThe default shell on Linux distributions
1992POSIX.2 standardises the shell command language#!/bin/sh portability means "POSIX sh"
2006bash 3.2 released (2006-10-11; 3.2.57, the last 3.2 patch release, is dated 2014-11-07 in the GNU archive)macOS still ships 3.2.57, which is what /bin/bash --version printed on the build host
2009bash 4.0 adds associative arrays, mapfile, ${x,,}Scripts that use them fail on stock macOS
2019macOS 10.15 makes zsh the default login shellInteractive shell changed; #!/bin/bash scripts still run bash 3.2 (Apple support page, saved)
2024POSIX.1-2024 (Issue 8) lists pipefail among the set -o optionsThe most useful bash-ism becomes standard

The primary documents are the GNU Bash Reference Manual and the POSIX Shell Command Language (Issue 8, IEEE Std 1003.1-2024); both are saved under pipeline/sources/shell-scripting-text-processing/ and quoted below where a rule matters.

The concept catalogue ​

Shells: bash vs sh vs zsh, POSIX sh, the shebang Must-know ​

In plain words: "the shell" is a family of programs that read commands. sh is the name of the portable, minimal dialect; bash is the common extended one; zsh is macOS's interactive default. The first line of a script, the shebang, tells the kernel which interpreter runs the file.

Common misunderstanding: "#!/bin/sh and #!/bin/bash are the same thing." On Debian and Ubuntu /bin/sh is dash, which has no arrays and no [[ ]]; on macOS /bin/sh is bash 3.2 in POSIX mode; on Alpine it is BusyBox ash. A script that works with bash script.sh can fail with sh script.sh.

Definition: The kernel reads the first line when you exec a file that starts with #!, and runs interpreter [one-optional-argument] script-path. #!/usr/bin/env bash finds bash on PATH (useful for Homebrew bash on macOS); #!/bin/bash is fixed and safer in a controlled image. Linux passes everything after the interpreter as ONE argument, so #!/usr/bin/env bash -e fails there; put options in the script with set.

1  $ ./deploy.sh --dry-run 1.4.2
2  kernel: file starts with "#!" -> read line 1: /usr/bin/env bash
3  kernel: execve("/usr/bin/env", ["/usr/bin/env", "bash", "./deploy.sh", "--dry-run", "1.4.2"])
4  env: searches PATH for "bash" -> execve("/opt/homebrew/bin/bash", ["bash", "./deploy.sh", ...])
5  bash: opens ./deploy.sh, ignores the "#!" line as a comment, runs the rest

Real scenario: A Docker image FROM alpine has no bash: #!/bin/bash entrypoints fail with exec ./entrypoint.sh: no such file or directory (the missing file is the interpreter). A Makefile recipe runs under /bin/sh and uses [[ ]]. A cron job that worked in your terminal fails because cron runs /bin/sh. A GitHub Actions run: step uses bash on Linux runners (bash -e {0} by default, bash --noprofile --norc -eo pipefail {0} when shell: bash is written explicitly) but PowerShell on Windows.

Environment/bin/sh isbash isDefault interactive
Debian, Ubuntudash5.xbash
RHEL, Fedora, Amazon Linuxbash (POSIX mode)5.xbash
Alpine (and most Docker slim images)BusyBox ashnot installed unless addedash
Distroless / scratchnonenonenone (no shell at all)
macOSbash 3.2.57 in POSIX mode3.2.57 (Homebrew: 5.x)zsh 5.9
GitHub Actions Linux runnerdash (Ubuntu)5.xn/a

Fix / how to choose: Write #!/usr/bin/env bash when you need arrays, [[ ]], pipefail on old systems or local; write #!/bin/sh and test with dash when the script must run in minimal images; never write zsh scripts for deployment. Check which you really have: the lab runs one program under bash, sh, dash, zsh and ksh and shows the differences.

bash
#!/bin/sh
# The same five-line program in every shell that is installed: where bash, POSIX sh and
# zsh disagree. Missing shells are skipped. Run with: sh scripts/shells-compared.sh
prog='
v="a b"
set -- $v;            echo "unquoted word split gives $# word(s)"
arr=(x y z) 2>/dev/null && echo "array literal ok, first=${arr[0]}${arr[1]}"
echo "BASH_VERSION=${BASH_VERSION:-unset} ZSH_VERSION=${ZSH_VERSION:-unset}"
[[ a == a ]] 2>/dev/null && echo "[[ ]] ok"
echo "local-in-function: $(f() { local x=1; echo $x; }; f 2>&1)"
echo "echo -e: $(echo -e "a\tb" | od -c | head -1 | cut -c9-30)"
'
for sh in bash sh dash zsh ksh; do
  if command -v "$sh" >/dev/null 2>&1; then
    printf '=== %s (%s)\n' "$sh" "$(command -v "$sh")"
    "$sh" -c "$prog" 2>&1 | sed 's/^/    /'
  else
    printf '=== %s: not installed\n' "$sh"
  fi
done

Exit status and set -euo pipefail Must-know ​

In plain words: every command ends with a number: 0 means success, anything else means failure. $? holds the last one. By default the shell keeps going after a failure; set -euo pipefail asks it to stop, to treat unset variables as errors and to look at every stage of a pipeline.

Common misunderstanding: "With set -e any failing command stops the script." The manual lists the exceptions: "The shell does not exit if the command that fails is part of the command list immediately following a while or until reserved word, part of the test in an if statement, part of any command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last (subject to the state of the pipefail shell option), or if the command's return status is being inverted with !." (Bash Reference Manual, set -e).

Definition: set -e (errexit), set -u (nounset), set -o pipefail. Without pipefail, "the exit status of a pipeline is the exit status of the last command in the pipeline"; with it, "the pipeline's return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully" (Bash manual, Pipelines). POSIX.1-2024 lists pipefail: "Derive the exit status of a pipeline from the exit statuses of all of the commands in the pipeline, not just the last (rightmost) command".

1  set -euo pipefail
2  grep -q ERROR app.log      # no match -> status 1 -> script exits here (often a surprise)
3  x=$(false)                  # assignment takes the substitution's status -> exits
4  local y=$(false)            # inside a function: status of `local`, which is 0 -> does NOT exit (SC2155)
5  false | true                # pipefail: status 1 -> exits; without pipefail: 0
6  yes | head -1               # yes dies of SIGPIPE (141); with pipefail the pipeline "fails"
7  [ -f x ] && echo yes        # fine: left side of && is exempt; but as the LAST line of a function it returns 1

Real scenario: a backup script runs pg_dump | gzip > db.gz; pg_dump fails (auth error), gzip succeeds on empty input, the script reports success and nobody notices for a month: pipefail plus a size check prevents it. A deploy script with cd "$DIR" on one line and rm -rf * on the next: when cd fails nothing stops the script and rm runs in the wrong directory (shellcheck SC2164 flags the unguarded cd; cd "$DIR" && rm -rf ./* or cd "$DIR" || exit 1 are the safe forms). set -u turns rm -rf "/$TYPO_DIR/" from "delete everything under /" into "unbound variable".

OptionWhat it doesGotcha
set -eExit when a simple command fails, outside the exempt contextsInactive inside any function called from an if, && or || context; Greg's Wiki BashFAQ/105 is the long list of surprises
set -uExpanding an unset variable is an errorUse ${var:-} for variables that may legitimately be unset; empty arrays on bash < 4.4 trip it
set -o pipefailPipeline status = last non-zero stagecmd | head can now "fail" with 141 (SIGPIPE); grep returning 1 on no match fails the pipeline
set -xTrace each command to stderr, with PS4 as the prefixPrints secrets; never leave on in CI logs
trap ... ERRRun a handler when a command would trigger -eNot inherited by functions without set -E

Fix / how to use it: start every script with set -euo pipefail, then handle expected failures explicitly: if grep -q x f; then, count=$(grep -c x f || true), cmd || rc=$?. Treat strict mode as a net for typos, and write the real error handling yourself. The lab's strict-mode.sh runs twelve small experiments; the key ones:

bash
#!/usr/bin/env bash
# What set -e, set -u and pipefail change, one experiment each. Each case runs in a
# child bash so the parent keeps going. Portable to bash 3.2 (macOS /bin/bash).
run() { printf '%s\n' "--- $1"; shift; bash -c "$@"; printf '    exit status: %d\n' "$?"; }

run "no options: the failing command is ignored"      'false; echo "still running"'
run "set -e: stops at the first failure"              'set -e; false; echo "never printed"'
run "set -e does not fire inside an if condition"     'set -e; if false; then :; fi; echo "reached"'
run "set -e is ignored on the left of ||"             'set -e; false || echo "handled"; echo "reached"'
run "no -u: a typo expands to the empty string"       'echo "rm -rf /$TYPO_DIR/"'
run "set -u: a typo is an error"                      'set -u; echo "rm -rf /$TYPO_DIR/"'
run "pipeline status is the LAST command's"           'false | true; echo "status was $?"'
run "set -o pipefail: any failure fails the pipeline" 'set -o pipefail; false | true; echo "status was $?"'
run "PIPESTATUS shows every stage"                    'false | true | false; echo "${PIPESTATUS[*]}"'
run "set -e and command substitution in assignment"   'set -e; x=$(false); echo "never printed"'
run "set -e is lost in 'local x=\$(cmd)' (SC2155)"    'set -e; f() { local x=$(false); echo "reached, x=[$x]"; }; f'
run "set -e is switched off inside functions called in a condition" 'set -e; f() { false; echo "f continued"; }; if f; then echo "f ok"; fi'
run "pipefail and SIGPIPE: head closes early, yes dies with 141" 'set -o pipefail; yes | head -1; echo "status was ${PIPESTATUS[0]} then $?"'
run "grep with no match returns 1: fatal under set -e unless guarded" 'set -e; echo abc | grep -q zzz; echo "never printed"'
run "guarded with || true"                            'set -e; echo abc | grep -q zzz || true; echo "reached"'
run "|| true hides real errors too: count, do not swallow" 'set -e; n=$(echo abc | grep -c zzz || true); echo "matches: $n"'

Real output (bash 3.2.57 on macOS; the status after an unbound variable is 127 on this bash and 1 on bash 5, so test for "non-zero", never for the number):

text
--- no options: the failing command is ignored
still running
    exit status: 0
--- set -e: stops at the first failure
    exit status: 1
--- set -e is ignored on the left of ||
handled
reached
--- set -u: a typo is an error
bash: TYPO_DIR: unbound variable
    exit status: 127
--- pipeline status is the LAST command's
status was 0
--- set -o pipefail: any failure fails the pipeline
status was 1
--- PIPESTATUS shows every stage
1 0 1
--- set -e is lost in 'local x=$(cmd)' (SC2155)
reached, x=[]
--- pipefail and SIGPIPE: head closes early, yes dies with 141
status was 141 then 141

Quoting, word splitting, globbing and IFS Must-know ​

In plain words: after the shell substitutes a variable it chops the result into words at spaces, tabs and newlines, then treats * and ? in each word as a file pattern. Double quotes stop both. Single quotes stop everything.

Common misunderstanding: "I only need quotes when the value contains a space." The value * expands to every filename in the directory; a value starting with - becomes an option; an empty value disappears and shifts the arguments. Quote always.

Definition: After parameter expansion, command substitution and arithmetic expansion, the results that were not in double quotes undergo word splitting (on the characters in IFS, default space, tab, newline) and then pathname expansion (globbing). "$@" expands to each positional parameter as its own word; "$*" is one word joined with the first character of IFS; unquoted $@ and $* are both split again. Pathname expansion then applies to every word that still contains an unquoted glob character, including literal ones you typed (ls data/*.csv); its results are final and are not split a second time.

What bash does to one command line, in order1 brace expansion {a,b}2 tilde expansion ~3 $var, $(cmd), $((1+2))left to right4 word splitting (IFS)5 globbing * ? [a-z]6 quote removalQuoting decides which steps still run'single quotes' -> steps 1-5 are skipped: text is literal$var inside single quotes stays the five characters $var"double quotes" -> step 3 runs; steps 4 and 5 do NOT"$f" is always exactly one word, whatever it containsunquoted $f -> steps 4 and 5 run on the VALUE"my report.txt" becomes two words; "*.txt" becomes a file listRule of thumb: quote every expansion ("$x", "$(cmd)", "$@", "${a[@]}")unless you want splitting or globbing, and then say so in a comment.
1  f='my report.txt'
2  rm $f              -> rm my report.txt          # two words: deletes "my" and "report.txt"
3  rm "$f"            -> rm "my report.txt"        # one word
4  p='*.txt'; ls $p   -> ls a.txt b.txt 'my report.txt'      # split first (one word), then glob; the three results are NOT split again
5  rm -rf $DIR/       -> rm -rf /                  # DIR unset, no set -u, no quotes: the classic
6  for i in $(ls); do # splits "my report.txt" into two iterations: use a glob instead

Real scenario: a script that renames uploaded files breaks on "Q3 report (final).pdf"; a for f in $(find ...) loop breaks on any space; docker run $OPTS image where OPTS="--env A=1 --env B=2" relies on splitting deliberately (the one legitimate use: say so in a comment and use an array instead).

SyntaxSplits?Globs?Expands $?Use for
$xyesyesyesAlmost never
"$x"nonoyesEvery variable
'$x'nononoLiteral text, regexes, awk and jq programs
$'a\tb'nonono (ANSI-C escapes)Tabs and newlines in bash
"${arr[@]}"each element is one wordnoyesPassing a list of arguments
"$*"joined with first char of IFSnoyesBuilding one string
$(cmd) unquotedyesyesyesAlmost never; quote it

What IFS is for: IFS=, read -r -a parts <<<"$line" splits one line on commas without touching the global value (the assignment applies to that one command). The safe-template sets IFS=$'\n\t' so that an accidental unquoted expansion no longer splits on spaces; the side effect is that "$*" now joins words with newlines, so the template's logger resets IFS locally.

Fix / how to use it: quote, use arrays for lists, -- before positional values that might start with - (rm -- "$f"), and shellcheck (SC2086 "Double quote to prevent globbing and word splitting", SC2046 for command substitution). The script below prints the argument counts so the effect is visible:

bash
#!/usr/bin/env bash
# Quoting, word splitting, globbing and IFS: unsafe versus safe, side by side.
# Runs in a scratch directory it creates itself; touches nothing else.
set -eu

work=$(mktemp -d "${TMPDIR:-/tmp}/pitfalls.XXXXXX")
trap 'rm -rf "$work"' EXIT
cd "$work"

touch 'my report.txt' 'a.txt' 'b.txt'

count_args() { printf '%d args:' "$#"; for a in "$@"; do printf ' [%s]' "$a"; done; printf '\n'; }

f='my report.txt'
echo "--- unquoted vs quoted variable (SC2086)"
count_args $f        # splits on IFS: 2 words
count_args "$f"      # 1 word

echo "--- unquoted glob in a variable"
pattern='*.txt'
count_args $pattern  # the glob is expanded AFTER variable expansion
count_args "$pattern"

echo "--- command substitution is split too (SC2046)"
count_args $(printf 'one two\n')
count_args "$(printf 'one two\n')"

echo "--- IFS: split only on commas"
line='a b,c d,e'
IFS=, read -r -a parts <<<"$line"
count_args "${parts[@]}"

echo "--- default values and trimming (POSIX forms)"
unset NAME
echo "[${NAME:-anonymous}] [${NAME-}] [${NAME:=set-now}] [${NAME}]"
echo "[${#NAME}] [${NAME%-now}] [${NAME#set-}]"

echo "--- arrays keep elements that contain spaces"
files=('my report.txt' 'a.txt')
count_args "${files[@]}"
count_args ${files[@]}
text
--- unquoted vs quoted variable (SC2086)
2 args: [my] [report.txt]
1 args: [my report.txt]
--- unquoted glob in a variable
3 args: [a.txt] [b.txt] [my report.txt]
1 args: [*.txt]
--- command substitution is split too (SC2046)
2 args: [one] [two]
1 args: [one two]
--- IFS: split only on commas
3 args: [a b] [c d] [e]

Variables and parameter expansion, default values, arrays Must-know ​

In plain words: name=value (no spaces around =) sets a variable; "$name" reads it. Inside the braces you can ask for a default, a length or a trimmed version without calling another program.

Common misunderstanding: "x = 5 works." It runs a command named x with arguments = and 5. And "variables are global to the file": they are global to the shell process, but a pipeline stage or $(...) runs in a subshell, and changes made there vanish.

Definition: POSIX parameter expansion forms (work in every sh): ${v:-default} (use default if unset or empty), ${v-default} (only if unset), ${v:=default} (also assign), ${v:?message} (error and exit if unset or empty), ${v:+alt} (alt if set and non-empty), ${#v} (length), ${v%suffix} and ${v%%suffix} (remove shortest or longest suffix), ${v#prefix} and ${v##prefix}. Bash additions: ${v^^} and ${v,,} (case, bash 4), ${v//old/new} (replace all), ${v:2:3} (substring), arrays.

1  unset NAME
2  echo "${NAME:-anonymous}"   -> anonymous           (NAME stays unset)
3  echo "${NAME:=set-now}"     -> set-now             (NAME is now set)
4  echo "${#NAME} ${NAME%-now} ${NAME#set-}"   -> 7 set now
5  file=/var/log/app.tar.gz
6  echo "${file##*/} ${file%.gz} ${file%%.*}"  -> app.tar.gz /var/log/app.tar .

Arrays (bash, ksh, zsh; not POSIX sh): files=('my report.txt' 'a.txt'), "${files[@]}" (every element, each one word), "${#files[@]}" (count), files+=("new"). Indexed arrays are 0-based in bash and 1-based in zsh. Associative arrays (declare -A m) need bash 4: on the macOS system bash the lab prints declare: -A: invalid option. mapfile/readarray and ${x,,} are bash 4 too.

NeedPOSIX formBash-only formPitfall
Default value${v:-x}same:- treats empty as unset; - does not
Required value${v:?msg}sameThe message goes to stderr and a non-interactive shell exits
Strip extension${f%.*}same% is the end, # is the start
Replacesed${v//a/b}Slow in a loop over large data
Lowercasetr 'A-Z' 'a-z'${v,,} (bash 4)tr ranges depend on locale
List of argsset -- a b c and "$@"arraysOnly one list in POSIX sh
Read a file into an arrayloop with readmapfile -t a <file (bash 4)read loops lose the last line without a newline unless || [ -n "$line" ]
Arithmetic$((a + b))((a < b))[ "$a" -lt "$b" ] errors on non-numbers

Scoping: local x limits a variable to a function (and its callees; this is dynamic scope, not lexical). export x copies it into the environment of child processes; it does not make the variable visible to the parent. A variable assigned inside cmd | while read ... is set in a subshell and lost, which is the most common "my counter is 0" bug (demonstrated in the loops script below).

Functions, conditionals, test and [[ ]], loops Must-know ​

In plain words: if runs a command and checks its status; [ ... ] is just a command that compares things and returns 0 or 1. Functions are named groups of commands that take $1, $2... and return a status, not a value.

Common misunderstanding: "A function returns its result with return." return only sets a 0-255 status. A function "returns" data by printing it and the caller captures it with $(f). And "[ $a = b ] is safe": when $a is empty the command becomes [ = b ] and fails with "unary operator expected".

Definition: [ is a command (also a builtin) whose last argument must be ]; test is the same without the bracket. [[ ]] is a bash/zsh/ksh keyword: it does no word splitting or globbing on its operands, supports == with glob patterns, =~ for regular expressions (groups in BASH_REMATCH), && and ||, and compares < and > as strings. (( )) does integer arithmetic.

Test[ ] / test (POSIX)[[ ]] (bash, zsh, ksh)
Empty / non-empty string[ -z "$s" ], [ -n "$s" ][[ -z $s ]]
String equality[ "$a" = "$b" ] (one =)[[ $a == $b ]] is a pattern match when the right side is unquoted
Numeric[ "$a" -lt "$b" ](( a < b )) (use this)
Files-e -f -d -L -r -w -x -ssame
AND, OR[ a ] && [ b ], or the obsolescent -a, -o[[ a && b ]]
Patterncase $s in pat) ... ;; esac[[ $s == pat* ]]
Regexgrep -E, expr[[ $s =~ ^re$ ]] (right side unquoted)
bash
#!/bin/sh
# POSIX sh on purpose: test, [ ], case, loops and functions that run in dash, bash and zsh.
# Compare with the bash-only [[ ]] shown at the end (run it with bash, not sh).
n=10; s='hello world'; empty=''

echo "--- [ ] is the command test(1): operands must be quoted, && is two commands"
[ "$n" -gt 5 ] && [ "$n" -lt 20 ] && echo "5 < n < 20"
[ -z "$empty" ] && echo "empty string is -z"
[ -n "$s" ] && echo "non-empty string is -n"
[ "$s" = 'hello world' ] && echo "string equality is a single ="

echo "--- numeric compare on a non-number is an error, not false"
[ "abc" -gt 5 ] 2>&1 || echo "status $? (2 = error, 1 = false)"

echo "--- file tests"
[ -d /tmp ] && echo "/tmp is a directory"
[ -f /etc/hosts ] && echo "/etc/hosts is a regular file"
[ -x /bin/sh ] && echo "/bin/sh is executable"

echo "--- case: pattern matching without [[ ]]"
for v in 1.4.2 v2 latest; do
  case $v in
    [0-9]*.[0-9]*.[0-9]*) echo "$v: semver" ;;
    v[0-9]*)              echo "$v: v-prefixed" ;;
    *)                    echo "$v: other" ;;
  esac
done

echo "--- loops: for over words, while over lines, until"
for f in a b c; do printf '%s ' "$f"; done; echo
printf 'one\ntwo three\n' | while IFS= read -r line; do echo "line=[$line]"; done
i=0; until [ "$i" -ge 3 ]; do i=$((i + 1)); done; echo "i=$i"

echo "--- functions: return is a status 0-255, output is stdout"
add() { echo $(($1 + $2)); }
is_even() { [ $(($1 % 2)) -eq 0 ]; }
echo "sum=$(add 2 3)"; is_even 4 && echo "4 is even"

echo "--- here-docs: expanded, quoted delimiter, and <<- with tab indentation"
cat <<EOT
Expanded: n=$n
EOT
cat <<'EOT'
Literal:  n=$n (quoted delimiter turns expansion off)
EOT
cat <<-EOT
	<<- strips leading TABs, so a here-doc can be indented inside a function
EOT
text
--- numeric compare on a non-number is an error, not false
scripts/conditionals.sh: line 13: [: abc: integer expression expected
status 2 (2 = error, 1 = false)
--- case: pattern matching without [[ ]]
1.4.2: semver
v2: v-prefixed
latest: other
bash
#!/usr/bin/env bash
# What [[ ]] adds over [ ] (bash, zsh, ksh; NOT POSIX sh). Runs on bash 3.2.
s='release-1.4.2'; empty=''
[[ $s == release-* ]]        && echo "glob match without quoting the variable"
[[ $s =~ ^release-([0-9]+)\.([0-9]+) ]] && echo "regex match, groups: ${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"
[[ -z $empty || $s == x ]]   && echo "|| and && inside [[ ]]; no word splitting on unquoted \$empty"
[ -z $empty ] && echo "[ -z \$empty ] works only by luck: it becomes [ -z ]"
[ $empty = x ] 2>&1 || echo "[ \$empty = x ] -> [ = x ] -> syntax error, status $?"
[[ $empty = x ]] || echo "[[ \$empty = x ]] is fine"
[[ 10 < 9 ]] && echo "[[ < ]] compares STRINGS: 10 < 9 is true"
(( 10 < 9 )) || echo "(( )) compares numbers: 10 < 9 is false"
text
glob match without quoting the variable
regex match, groups: 1 4
[ -z $empty ] works only by luck: it becomes [ -z ]
scripts/conditionals-bash.sh: line 8: [: =: unary operator expected
[ $empty = x ] -> [ = x ] -> syntax error, status 2
[[ < ]] compares STRINGS: 10 < 9 is true
(( )) compares numbers: 10 < 9 is false

Loops: for x in a b c, for f in ./*.log (glob; guard the no-match case with [ -e "$f" ] || continue), while IFS= read -r line (reads lines; -r keeps backslashes, IFS= keeps leading spaces), until cmd, for ((i=0;i<n;i++)) (bash), break, continue. case for pattern dispatch. Functions: name() { ...; }, local for variables, return N for status, output through stdout, "$@" to pass arguments on.

Here-docs and command substitution Important ​

In plain words: a here-document feeds a block of text to a command's standard input. Command substitution $(cmd) runs a command and pastes its output in place.

Common misunderstanding: "Here-doc bodies are literal." With an unquoted delimiter the body undergoes $var, $(cmd) and backtick expansion; <<'EOT' (quoted) keeps it literal. And "$(cmd) keeps trailing newlines": it strips all of them, which matters when the data ends in meaningful whitespace.

Definition: cmd <<EOT ... EOT (expanded body), cmd <<'EOT' (literal body), cmd <<-EOT (leading TABs, not spaces, are stripped so the block can be indented), cmd <<<"$string" (here-string, bash). Prefer $(cmd) over backticks: it nests and needs less escaping. Process substitution <(cmd) (bash, zsh, ksh; not POSIX) presents a command's output as a file name, useful to avoid the pipe-subshell bug: while read -r l; do ...; done < <(cmd).

1  cat <<EOT > /etc/app.conf     # unquoted: $HOME and $(hostname) are expanded NOW
2  host=$(hostname)
3  EOT
4  cat <<'EOT' > run.sh           # quoted: written exactly as typed, $1 stays $1
5  echo "arg: $1"
6  EOT

Real scenario: generating an Nginx config or a systemd unit from a script with a here-doc; passing a multi-line SQL script to psql with psql -v ON_ERROR_STOP=1 <<'SQL' ... SQL; capturing a version with ver=$(git describe --tags). The trap: local v=$(cmd) hides cmd's status (SC2155); declare, then assign.

Pipes and redirection: stdin, stdout, stderr, 2>&1, tee Must-know ​

In plain words: every program has three numbered streams: 0 (stdin), 1 (stdout), 2 (stderr). | connects the stdout of one program to the stdin of the next. > sends stdout to a file. Errors travel on stream 2, so they do not go through the pipe.

Common misunderstanding: "cmd > out.log 2>&1 and cmd 2>&1 > out.log are the same." Redirections are applied left to right. In cmd > out.log 2>&1 fd 1 goes to the file first and fd 2 then copies it, so both streams are in the file. In cmd 2>&1 > out.log fd 2 copies the terminal first and only then fd 1 goes to the file, so stderr still reaches the terminal (see the diagram near the top; Bash manual, Redirections).

Definition: > truncate, >> append, < read, 2>file, 2>&1 (make fd 2 a copy of fd 1), &>file (bash shorthand for both; not POSIX), >/dev/null, << here-doc, | pipe, |& (bash: pipe both streams). Each stage of a pipeline is its own process (a subshell for builtins and compound commands), started concurrently; a pipe has a bounded buffer (pipe(7): 16 pages, 65,536 bytes, on a typical Linux system) and blocks the writer when full, which is how yes | head -1 terminates: head exits, the write end gets SIGPIPE.

1  cmd1 | cmd2 | cmd3      fork 3 processes, connect stdout(cmd1)->stdin(cmd2)->stdin(cmd3)
2  cmd >out 2>&1           fd1 -> out; fd2 -> where fd1 points (out)      both in the file
3  cmd 2>&1 >out           fd2 -> where fd1 points (terminal); fd1 -> out  stderr on screen
4  cmd 2>/dev/null         discard errors (and every diagnostic you will want later)
5  cmd | tee run.log | grep ERROR     tee copies its stdin to run.log AND to stdout
6  cmd 2>&1 | tee -a run.log          capture both streams, append, still show them

Real scenario: cron mails you any output, so a script that is silent on success and prints the log on failure makes mail meaningful; CI logs interleave stdout and stderr only if both go to the same pipe (2>&1); docker run ... | tee build.log keeps a log while you watch; logging functions write to stderr so stdout stays a clean data channel for the next pipeline stage. tee writes to its own stdout and to each file; sudo tee is the way to write a root-owned file from an unprivileged pipeline (echo x | sudo tee /etc/f, because sudo echo x > /etc/f redirects as you, not as root).

ConstructMeaningGotcha
cmd > fTruncate f BEFORE cmd startssort f > f empties f first: use sort -o f f or a temp file
cmd >> fAppendConcurrent appends of short lines are usually atomic; do not rely on it for big writes
cmd < fstdin from filecmd < f and cat f | cmd differ in that the first lets cmd seek
exec 3>fileOpen fd 3 for the rest of the scriptThis is how flock 9 locks work
cmd | tee fCopyWithout set -o pipefail a failure of cmd is hidden by tee's success
cmd &>/dev/nullBash-only both streamsIn sh it is >/dev/null 2>&1

find and xargs Must-know ​

In plain words: find walks a directory tree and tests each entry; xargs turns a stream of names into the arguments of another command. File names can contain spaces and even newlines, so the only safe separator is the NUL byte.

Common misunderstanding: "ls | xargs rm is fine." ls output cannot be parsed reliably (names with spaces and newlines), and xargs splits on whitespace and treats quotes specially. The Wooledge wiki page "Parsing ls" exists because of this; shellcheck reports SC2012.

Definition: find DIR -type f -name '*.log' -mtime +7 -print0 | xargs -0 rm -- is the safe form. -print0 and xargs -0 use NUL separators (both are in GNU findutils and BSD); find ... -exec cmd {} + batches arguments without xargs and is POSIX; -delete removes without forking. xargs -n1 runs one command per item; xargs -P4 runs four in parallel; GNU xargs runs the command once even on empty input unless you pass -r; the FreeBSD xargs does not run it on empty input and accepts -r for GNU compatibility (FreeBSD xargs(1), saved; macOS derives from it, and the build host accepted -r), so -r is safe on both.

1  find logs -type f -name '*.log' -print0
2    | xargs -0 -n1 sh -c 'printf "<%s>\n" "$1"' _
3  <logs/a.log>
4  <logs/my file.log>
5  <logs/new
6  line.log>
GoalCommandPortability
Delete old filesfind /var/tmp/app -type f -mtime +7 -delete-delete is in GNU and BSD find, not in strict POSIX
Compress in parallelfind . -name '*.log' -print0 | xargs -0 -P4 -n10 gzip-P is in GNU and BSD xargs, not POSIX
Run per file with a shellfind . -name '*.sh' -exec sh -c 'for f; do shellcheck "$f"; done' _ {} +POSIX
Newest filels -t | head -1 (breaks on odd names); in GNU find . -printf '%T@ %p\n' | sort -n | tail -1-printf is GNU only
Files changed in 24 hfind . -mtime -1POSIX
Case-insensitive namefind . -iname '*.JPG'GNU and BSD
bash
#!/usr/bin/env bash
# Looping over files safely: globs, find -print0 | xargs -0, and while IFS= read -r.
set -eu
work=$(mktemp -d "${TMPDIR:-/tmp}/loops.XXXXXX"); trap 'rm -rf "$work"' EXIT
cd "$work"
mkdir logs; touch 'logs/a.log' 'logs/my file.log' "logs/new
line.log" 'logs/.hidden.log' 'logs/b.txt'

echo "--- ls | wc -l counts lines, not files: 4 visible files, one name contains a newline (SC2012)"
ls logs | wc -l | tr -d ' '

echo "--- glob loop: safe, no subprocess; always guard the no-match case"
for f in logs/*.log; do [ -e "$f" ] || continue; printf '[%s] ' "$f"; done; echo

echo "--- find -print0 | xargs -0: NUL is the only byte a filename cannot contain"
find logs -type f -name '*.log' -print0 | xargs -0 -n1 sh -c 'printf "<%s>\n" "$1"' _

echo "--- find -exec ... + (POSIX, no xargs needed)"
find logs -type f -name '*.log' -exec ls -1 {} + | wc -l | tr -d ' '

echo "--- while IFS= read -r with a NUL-separated stream (bash: read -d '')"
find logs -type f -name '*.log' -print0 | while IFS= read -r -d '' f; do printf '(%s)\n' "$f"; done

echo "--- the classic bug: variables set inside a piped while are lost (subshell)"
count=0; printf 'a\nb\n' | while read -r _; do count=$((count + 1)); done; echo "count after pipe: $count"
count=0; while read -r _; do count=$((count + 1)); done < <(printf 'a\nb\n'); echo "count with process substitution: $count"

echo "--- find -delete / -mtime are portable; -printf and -regextype are GNU only"
find logs -type f -name '*.txt' -mtime -1 -print
text
--- ls | wc -l counts lines, not files: 4 visible files, one name contains a newline (SC2012)
5
--- find -print0 | xargs -0: NUL is the only byte a filename cannot contain
<logs/a.log>
<logs/.hidden.log>
<logs/my file.log>
<logs/new
line.log>
--- the classic bug: variables set inside a piped while are lost (subshell)
count after pipe: 0
count with process substitution: 2

grep and regular expressions: ERE vs BRE Must-know ​

In plain words: grep prints the lines that match a pattern. The pattern language comes in flavours: the "basic" one treats + ? | ( ) as plain characters unless you backslash them; the "extended" one (grep -E) treats them as operators.

Common misunderstanding: "grep 'a+' finds one or more a." In a BRE the + is a literal plus (GNU grep accepts \+ as an extension; strict POSIX BRE has no +). Use grep -E 'a+'. And "grep -P is available everywhere": it is GNU only; macOS's grep rejects it (grep: invalid option -- P).

Definition: grep [-E|-F] [-i] [-v] [-c] [-n] [-o] [-q] [-r] [-w] [-x] [-l] [-h] [-A n -B n -C n] PATTERN [FILE...]. Exit status: 0 = a line selected, 1 = no line selected, 2 = error. -F is a fixed-string search (no regex, fastest, safest for user input); -q is quiet (use in if); -o prints only the match; -r recurses (-R follows symlinks).

FeatureBRE (default)ERE (-E)PCRE (-P, GNU only)
Repeat*, \{n,m\}*, +, ?, {n,m}same, plus lazy *?
Alternation| (GNU extension)| is plain |: a|bsame
Group\( \)( )( ), (?: )
Back-reference\1\1 (GNU)\1
Classes[[:digit:]], [a-z]same\d, \w, \s
Anchors^ $^ $^ $ \b
Wheregrep, sed (default)grep -E, sed -E/-r, awkGNU grep, PHP/Go-style regex

Real scenario: count 5xx responses (grep -cE '" 5[0-9]{2} ' access.txt); check a service is mentioned (grep -q); find TODOs recursively (grep -rn --include='*.go' TODO .); the status codes 1 (none) versus 2 (error) distinguish "clean" from "file missing".

1  grep -E '" 5[0-9]{2} ' access.txt        -> 2 lines (500, 502)
2  grep    'orders/[0-9][0-9]*' access.txt  -> 5 lines   (BRE: no +, so repeat the class and *)
3  grep -E 'orders/[0-9]+'      access.txt  -> 5 lines   (ERE: + is an operator)
4  grep -F 'a.b' file                       -> literal "a.b", the dot is not "any character"
5  grep -q zzz file; echo $?                -> 1  (no match, not an error)
6  grep -q zzz /missing; echo $?            -> 2  (error)

sed: substitutions and in-place edits Must-know ​

In plain words: sed reads lines, applies edit commands and prints the result. The workhorse is s/old/new/, with g to replace every match on a line.

Common misunderstanding: "sed -i works the same everywhere." GNU sed takes an optional suffix glued to the flag (-i.bak, or -i with none); BSD/macOS sed requires a separate argument (-i '' for none, -i .bak). Apple's man page: "-I extension Edit files in-place, saving backups with the specified extension. If a zero-length extension is given, no backup will be saved. It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted". The portable form is sed -i.bak 's/x/y/' f && rm f.bak.

Definition: sed [-E] [-n] [-i[SUFFIX]] 'script' [file...]. Commands: s/re/repl/flags (flags: g, p, I GNU, number), d delete, p print (with -n), a, i, c (GNU one-line forms differ on BSD), y/abc/xyz/, ranges /start/,/end/ or 3,5. In the replacement, & is the whole match and \1..\9 are groups. The delimiter can be any character (s|/usr/bin|/opt|g). BRE is the default; -E (both GNU and BSD) selects ERE; -r is GNU-only.

1  echo 'orders-2026-11-29.log' | sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3.\2.\1/'   -> orders-29.11.2026.log
2  sed -i.bak 's/^PORT=.*/PORT=9090/' .env && rm .env.bak     # portable in-place edit with backup
3  sed -n '/ERROR/,/^$/p' app.log                              # print each error block, -n suppresses autoprint
4  sed '/^#/d;/^$/d' conf                                      # drop comment lines and blank lines
5  sed 's/%20/ /g'                                             # decode one escape (not a URL decoder)
TaskPortable formGNU-only shortcutWhy it differs
Edit in placesed -i.bak ... f; rm f.baksed -i ... fBSD needs a suffix argument
Tab in replacementsed "s/ /$(printf '\t')/"sed 's/ /\t/'POSIX leaves \t undefined; recent macOS accepts it, older BSDs do not
Newline in replacementbackslash then a real newline\nSame
+ ? | in BREsed -E\+ \? |GNU extensions to BRE
Case-insensitive[Ee]rrors/error/X/II flag is GNU
Case conversionawk toupper\U...\EGNU only
Multi-line editawk or perl -0pesed -zNUL-separated mode is GNU

Real scenario: rewrite image: ...:1.4.1 to the new tag in a Kubernetes manifest or Helm values file in CI (sed -i.bak -E "s|(image: ghcr.io/example/orders-api):.*|\1:$TAG|" values.yaml); strip Windows line endings (sed 's/\r$//'); comment out a line. For structured files (YAML, JSON) prefer yq and jq: a regex edit breaks on anchors, multi-line strings and flow style. The lab's portability script shows the real BSD error for the GNU-style call: sed: 1: "/var/folders/...": invalid command code f.

awk: fields and aggregations Must-know ​

In plain words: awk splits every line into fields ($1, $2, ... $NF is the last) and runs your small program on each line, with variables that persist and a final END block, so it is the shortest way to "group by column 1 and sum column 3".

Common misunderstanding: "awk is old and I should use Python." For column work in a pipeline, awk's one-pass streaming over gigabytes with a few bytes of code is hard to beat; Python wins once you need structures, tests or libraries (see when to switch). Also: awk is not one program: macOS ships the "one true awk" (version 20200816 here), Debian ships mawk, many Linux systems gawk; gawk-only features (gensub, asort, PROCINFO, -v arrays, strftime) fail elsewhere.

Definition: awk [-F fs] [-v var=value] 'pattern { action } ... END { ... }' [file...]. Built-ins: NR (record number), NF (field count), FS and OFS (field separators), $0 (whole line), BEGIN and END blocks, associative arrays n[key]++, functions split, substr, length, sub, gsub, printf, toupper. A pattern without an action prints the line; $9 >= 500 is a numeric comparison because the field looks numeric.

1  awk '{ c = substr($9,1,1) "xx"; n[c]++ } END { for (k in n) print k, n[k] }' access.txt | sort
2      -> 2xx 9 / 4xx 1 / 5xx 2
3  awk '$9 >= 500 { e++ } END { printf "%d of %d = %.1f%%\n", e, NR, 100*e/NR }' access.txt
4      -> 2 of 12 = 16.7%
5  awk -F, 'NR > 1 && $3 == "paid" { s += $4 } END { print s }' orders.csv
6      -> 195.75       (header skipped; naive CSV: breaks if a field contains a comma)
TaskProgramNotes
Print columnsawk '{print $1, $NF}'Default FS collapses runs of blanks
CSV without quoted commasawk -F, '...'Quoted fields need a real parser (Go encoding/csv, Python csv)
Sum / average{s+=$3} END{print s, s/NR}Uninitialised variables are 0 / empty
Group by{n[$1]++} END{for(k in n) print k, n[k]}for (k in n) order is unspecified: pipe to sort
Max per key$3>m[$1]{m[$1]=$3}Compares as numbers when both look numeric
Join / dedupe!seen[$0]++Prints the first occurrence of each line, keeps order
Pass a shell valueawk -v lim="$LIMIT" '$3>lim'Never splice shell variables into the program text

cut, sort, uniq, tr, wc Must-know ​

In plain words: five tiny filters that, combined, answer most "how many of each" questions: cut picks columns, sort orders lines, uniq -c counts neighbours, tr swaps characters, wc counts.

Common misunderstanding: "uniq removes duplicates." It only collapses adjacent duplicate lines, which is why it is always preceded by sort. And "sort -n and sort agree": sort compares text in the current locale (so 10 sorts before 9, and LC_ALL=C changes the order of upper and lower case), while -n compares numbers.

Definition: cut -d' ' -f1,3 (fields) or -c1-10 (characters; bytes with -b; multibyte text needs a locale-aware cut, see the encoding chapter); sort [-n] [-r] [-k N] [-t,] [-u] [-h]; uniq [-c] [-d] [-u]; tr 'a-z' 'A-Z', tr -d '\r', tr -s ' ' (squeeze), tr -c (complement); wc -l -w -c (macOS pads the number with spaces: tr -d ' ' or use awk 'END{print NR}').

1  cut -d' ' -f1 access.txt | sort | uniq -c | sort -rn | head -3
2     5 203.0.113.7
3     3 198.51.100.4
4     2 198.51.100.9
5  awk '{print $NF, $6, $7}' access.txt | sort -rn | head -3 | tr -d '"'
6  1.002 POST /orders
ToolFlagMeaningPortability
sort-k2,2nSort by field 2, numericallyPOSIX
sort-VVersion sort (1.9 before 1.10)GNU; newer macOS has it, older does not
sort-hHuman-readable sizes (10K, 2M)GNU, recent BSD
sort-uUniquePOSIX
sort-S 1G -T /tmpBuffer size and temp dirGNU
uniq-cPrefix countsPOSIX
tr-d '\r'Delete charactersPOSIX
wc-lLines (newline count)POSIX
head-n -3All but the last 3 linesGNU only
tail-n +2From line 2 (skip a header)POSIX
Which tool for this text?What is the input?lines, find which: grep -E / -Flines, rewrite part: sed s///columns, sum or group: awkJSON: jq YAML or TOML: yqfixed columns, count, sort: cut sort uniq tr wcStop and use Go or Python when- the script passes ~100 lines- you need maps of structs, retries with backoff, concurrency- you parse CSV with quoted commas- you handle money or time zones- you want unit tests and one binary- the same logic runs on every OSPipeline rule of thumbFilter early (grep), reshape (sed, awk, jq), aggregate (sort | uniq -c, awk), present last (head, column).Keep each stage reading stdin and writing stdout, so any stage can be swapped for a Go binary later.

jq filters and yq Must-know ​

In plain words: jq is sed for JSON: you write a small filter, it reads JSON values and prints the result. yq does the same for YAML. Use them instead of grep and sed whenever the input is structured.

Common misunderstanding: "I can parse JSON with grep and cut." One extra space, a reordered key or an escaped quote breaks it silently. And the reverse trap: building JSON by string concatenation (echo "{\"name\": \"$n\"}") breaks on any quote in $n; let jq -n --arg build it.

Definition (jq 1.6/1.7): a filter is applied to each input value. .a.b path, .[] iterate, | pipe, , multiple outputs, select(cond), map(f), group_by(.k), add, length, // (alternative: .email // "n/a"), -r raw strings, -c compact, -e exit status from the last output (jq's manual: 0 if the last output was neither false nor null, 1 if it was false or null, 4 if no valid result was ever produced; the lab shows exit 4), --arg name value (string), --argjson name json, @csv, @tsv, @uri, @sh. yq here means mikefarah's Go implementation (v4), whose syntax is jq-like; there is also the unrelated Python yq wrapper around jq, so check yq --version.

1  jq -r '.orders[] | select(.status == "paid") | .id' orders.json        -> 1001, 1003
2  jq '[.orders[] | select(.status=="paid") | .total] | add' orders.json -> 195.75
3  jq -r '.orders[] | [.customer.name, (.customer.email // "n/a")] | @tsv' orders.json
4  jq -n --arg name 'Ada "the first" Lovelace' --argjson qty 2 '{customer: $name, qty: $qty}'
5  yq '.service.replicas' config.yaml                                      -> 3
6  yq -i '.service.image = "ghcr.io/example/orders-api:1.4.3"' config.yaml  # in place; expected, not run
bash
#!/usr/bin/env bash
# jq filters on data/orders.json (jq 1.6+; the macOS 15+ /usr/bin/jq is jq-1.7.1-apple).
# yq (mikefarah, v4) lines are shown for data/config.yaml and run only if yq exists.
set -euo pipefail
cd "$(dirname "$0")/../data"

echo "--- paid order ids"
jq -r '.orders[] | select(.status == "paid") | .id' orders.json

echo "--- name and email, with a default for null"
jq -r '.orders[] | [.customer.name, (.customer.email // "n/a")] | @tsv' orders.json

echo "--- reshape into a new object per order"
jq -c '.orders[] | {id, who: .customer.name, lines: (.items | length)}' orders.json

echo "--- aggregate: revenue of paid orders (reduce via add)"
jq '[.orders[] | select(.status == "paid") | .total] | add' orders.json

echo "--- group_by + map"
jq -c '.orders | group_by(.status) | map({status: .[0].status, n: length, sum: (map(.total) | add)})' orders.json

echo "--- flatten nested arrays"
jq -r '.orders[] | .id as $id | .items[] | [$id, .sku, .qty] | @csv' orders.json

echo "--- exit status for scripts: -e fails when the last output is false or null"
jq -e '.orders[] | select(.id == 4242)' orders.json >/dev/null || echo "no such order (jq -e exit $?)"

echo "--- build JSON safely from shell variables (never with string concatenation)"
name='Ada "the first" Lovelace'
jq -n --arg name "$name" --argjson qty 2 '{customer: $name, qty: $qty}'

if command -v yq >/dev/null 2>&1; then
  echo "--- yq v4: read and edit YAML"
  yq '.service.replicas' config.yaml
  yq '.service.env[] | select(.name == "PORT") | .value' config.yaml
  yq '.service.replicas = 5' config.yaml
else
  echo "(yq not installed here: the three yq lines above are expected, not run)"
fi
text
--- paid order ids
1001
1003
--- name and email, with a default for null
Grace Hopper	n/a
--- aggregate: revenue of paid orders (reduce via add)
195.75
--- group_by + map
[{"status":"paid","n":2,"sum":195.75},{"status":"pending","n":1,"sum":30.00}]
--- exit status for scripts: -e fails when the last output is false or null
no such order (jq -e exit 4)
--- build JSON safely from shell variables (never with string concatenation)
{
  "customer": "Ada \"the first\" Lovelace",
  "qty": 2
}
(yq not installed here: the three yq lines above are expected, not run)

This output is from the macOS system jq-1.7.1-apple on the build host; 30.00 printed as written because jq 1.7 preserves the literal of a number it does not modify, which jq 1.6 does not. Do not rely on number formatting across jq versions. yq was not installed here, so its three lines are expected, not run.

Real scenario: read the replica count from a Helm values file, bump an image tag in a Kubernetes manifest from CI, extract the IDs from an API response, turn a JSON array into a CSV, validate that a response contains the field you need (jq -e). Neither tool is a schema validator.

curl in scripts Must-know ​

In plain words: curl talks to a URL. By default it is a friendly download tool, not a script-safe client: an HTTP 404 or 500 still counts as success if the transfer itself worked.

Common misunderstanding: "curl exits non-zero when the server returns an error." It does not unless you pass --fail (-f), which makes HTTP status 400 and up exit with code 22 (and --fail-with-body keeps the response body for diagnostics). Another: --retry retries everything; it retries only "transient" errors: per the curl manual "a timeout, an FTP 4xx response code or an HTTP 408, 429, 500, 502, 503, 504, 522 or 524 response code".

Definition: the script-safe baseline is curl --fail --silent --show-error --location --connect-timeout 5 --max-time 30 --retry 3 URL. -w '%{http_code}' prints the status; -o file writes the body; -K - reads options (such as an Authorization header) from stdin so the token never appears in ps; -d @file or --data-binary @file sends a file; --retry-connrefused retries "connection refused" (a service still starting); curl exit codes: 6 could not resolve host, 7 failed to connect, 22 HTTP error with --fail, 28 timeout.

NeedFlagsWhy
Fail on 4xx and 5xx--fail or --fail-with-bodyOtherwise a 500 page is "success"
No progress bar, still show errors-sS (--silent --show-error)Logs stay readable
Follow redirects-LNot on by default
Bound the time--connect-timeout N --max-time NNo default total timeout: a hung server hangs the script
Retry transient failures--retry 3 --retry-delay 2 --retry-connrefused--retry-delay disables the exponential backoff (1 s, doubling up to 10 min); the server's Retry-After is honoured
Status code-o /dev/null -w '%{http_code}'Branch on 200 vs 429
JSON body-H 'Content-Type: application/json' --data-binary @body.json-d strips newlines; --data-binary does not
Secret header-K - with the header on stdinCommand-line arguments are visible in the process list
bash
#!/usr/bin/env bash
# curl in scripts against a throwaway local HTTP server (python3 -m http.server is NOT used;
# a 10-line Python handler gives us 200, 503-then-200 and 404 on demand).
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
work=$(mktemp -d "${TMPDIR:-/tmp}/curl-demo.XXXXXX")
srv_pid=""
cleanup() {
  local rc=$?
  if [ -n "$srv_pid" ]; then kill "$srv_pid" 2>/dev/null || true; wait "$srv_pid" 2>/dev/null || true; fi
  rm -rf "$work"
  exit "$rc"
}
trap cleanup EXIT

cat >"$work/server.py" <<'PY'
import http.server, sys
hits = {"flaky": 0}
class H(http.server.BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def do_GET(self):
        if self.path == "/ok":    code, body = 200, b'{"status":"ok"}'
        elif self.path == "/flaky":
            hits["flaky"] += 1
            code, body = (503, b"try later") if hits["flaky"] < 3 else (200, b'{"status":"recovered"}')
        else:                     code, body = 404, b'{"error":"not found"}'
        self.send_response(code); self.send_header("Content-Type", "application/json"); self.send_header("Content-Length", str(len(body))); self.end_headers(); self.wfile.write(body)
http.server.HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
PY
port=18765
python3 "$work/server.py" "$port" & srv_pid=$!
for _ in 1 2 3 4 5 6 7 8 9 10; do curl -s -o /dev/null "http://127.0.0.1:$port/ok" && break; sleep 0.3; done
base="http://127.0.0.1:$port"

echo "--- default curl: a 404 is exit 0 (the transfer worked)"
curl -s "$base/missing"; echo " -> exit $?"

echo "--- --fail: HTTP errors (>= 400) become exit 22"
rc=0; curl -s --fail "$base/missing" || rc=$?; echo "exit $rc"

echo "--- status code and timing via --write-out, body to a file"
curl -s -o "$work/body" -w '%{http_code} %{content_type}\n' "$base/ok"; cat "$work/body"; echo

echo "--- retries: 503 is transient, curl retries it (--retry covers timeouts and HTTP 408, 429, 500, 502, 503, 504, 522, 524)"
rc=0; curl -s --fail --retry 3 --retry-delay 0 "$base/flaky" || rc=$?; echo " -> exit $rc"

echo "--- always bound the time"
curl -s --fail --connect-timeout 2 --max-time 5 "$base/ok" >/dev/null && echo "bounded request ok"

echo "--- parse the answer with jq and fail the script if the field is wrong"
curl -s --fail "$base/ok" | jq -e '.status == "ok"' >/dev/null && echo "status field ok"

echo "--- connection refused is exit 7"
rc=0; curl -s --connect-timeout 1 "http://127.0.0.1:1/" || rc=$?; echo "exit $rc"
text
--- default curl: a 404 is exit 0 (the transfer worked)
{"error":"not found"} -> exit 0
--- --fail: HTTP errors (>= 400) become exit 22
exit 22
--- status code and timing via --write-out, body to a file
200 application/json
{"status":"ok"}
--- retries: 503 is transient, curl retries it
{"status":"recovered"} -> exit 0
--- connection refused is exit 7
exit 7

Real scenario: a deploy script polls /healthz with --retry 5 --retry-connrefused for a service that takes 10 seconds to bind its port; a cron job calls a webhook and must alert on 5xx. The curl manual also warns that a retry after a partially received body written to stdout "may produce duplicate data": write to a file with -o.

trap, cleanup and temp files with mktemp Must-know ​

In plain words: trap 'command' SIGNAL... registers a command to run when the script gets a signal or exits. Use it to delete the temp files and release the lock, whatever happened.

Common misunderstanding: "trap ... EXIT covers everything." It runs on normal exit, exit and on signals the shell handles by exiting (INT, TERM, HUP, if you also trap them to call exit), but NEVER on kill -9 (SIGKILL), and the status is kept: a trap on EXIT does not change $? unless the handler itself calls exit with another value (bash -c 'trap "true" EXIT; exit 7' still exits 7). The bash manual: "Any trap on EXIT is executed before the shell terminates."

Definition: trap 'handler' EXIT (and ERR, DEBUG, RETURN in bash; INT TERM HUP), trap - EXIT resets, trap -p lists. A signal that arrives while a foreground command runs is handled when that command finishes: the lab's SIGTERM test needed about three seconds because the child (wc blocked on a pipe) was still running. mktemp creates a file or directory with an unpredictable name and safe permissions: mktemp -d "${TMPDIR:-/tmp}/job.XXXXXX" works on GNU and BSD (always give an explicit template ending in XXXXXX; the bare form differs between versions); the man page says it creates "a temporary file or directory, safely". Never use /tmp/job.$$ or /tmp/job.tmp: predictable names are a symlink-attack and collision risk.

1  tmp=$(mktemp -d "${TMPDIR:-/tmp}/job.XXXXXX")        # 0700, unique
2  cleanup() { rc=$?; trap - EXIT; rm -rf "$tmp"; exit "$rc"; }
3  trap cleanup EXIT
4  trap 'exit 130' INT; trap 'exit 143' TERM; trap 'exit 129' HUP    # signals become EXIT, so cleanup runs once
5  ... work in "$tmp" ...
6  mv "$tmp/result" "$OUT.new" && mv "$OUT.new" "$OUT"   # atomic publish within one filesystem
A script that is safe to run from cron, CI or by hand1 set -euo pipefailfail loudly, no typos2 getopts, usage, -n dry runexit 2 on bad input3 trap cleanup EXIT INT TERMinstalled BEFORE resources4 lock: mkdir or flock -nbusy: exit 3 (or 0 for cron)5 mktemp -d scratch dir0700, unpredictable name6 the work (run() wrapper)dry run prints, does not act7 write result to temp file, then mvrename is atomic: readers never see half a file8 EXIT trap: rc=$? first, rm -rf tmp,release lock, exit "$rc"Exit statuses used by this chapter's template0 ok 2 usage error 3 lock held 4 input unreadable 5 health check failed (deploy.sh)126 found but not executable 127 command not found 128+N killed by signal N (130 INT, 143 TERM)kill -9 skips every trap: only flock (kernel-held) and mktemp-in-TMPDIR cleaners survive it.

Real scenario: a script that downloads a 2 GB archive and extracts it fills the disk when it is killed halfway, every night, because nothing removes the extraction directory; a report generator that writes report.csv in place leaves a half-file that a consumer reads; mv of a temp file in the same directory fixes it, because rename(2) within one filesystem is atomic (across filesystems mv copies and is not).

Fix / how to use it: the full skeleton is the next block. Its cleanup captures $? on the first line, disarms the trap so it cannot re-enter, removes the temp directory and the lock, and exits with the original status.

bash
#!/usr/bin/env bash
# safe-template.sh: the skeleton every operational script starts from.
# Strict mode, usage, getopts, logging to stderr, dry-run, a temp dir that is always
# removed, a portable lock, and a cleanup trap that preserves the exit status.
# Works on bash 3.2 (macOS) and bash 5 (Linux). No GNU-only flags.
set -euo pipefail
IFS=$'\n\t'

readonly PROG=${0##*/}
DRY_RUN=0
VERBOSE=0
OUTPUT=""

usage() {
  cat <<USAGE
Usage: $PROG [-n] [-v] [-o FILE] INPUT...
  -n        dry run: print what would change, change nothing
  -v        verbose logging
  -o FILE   write the report to FILE (default: stdout)
  -h        this help
Exit status: 0 ok, 2 usage error, 3 lock held, other = failed step.
USAGE
}

log() { # log LEVEL message...  (stderr keeps stdout clean for data)
  local level=$1 IFS=' '; shift     # IFS above is newline+tab: "$*" would join words with newlines
  printf '%s %-5s %s: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$level" "$PROG" "$*" >&2
}
info()  { log INFO "$@"; }
debug() { if [ "$VERBOSE" -eq 1 ]; then log DEBUG "$@"; fi; }
die()   { log ERROR "$1"; exit "${2:-1}"; }   # die MESSAGE [STATUS]

run() { # run a mutating command, or only print it in dry-run mode
  if [ "$DRY_RUN" -eq 1 ]; then
    { printf 'DRY-RUN:'; printf ' %q' "$@"; printf '\n'; } >&2
  else
    debug "exec: $(printf '%q ' "$@")"
    "$@"
  fi
}

while getopts ':nvo:h' opt; do
  case $opt in
    n) DRY_RUN=1 ;;
    v) VERBOSE=1 ;;
    o) OUTPUT=$OPTARG ;;
    h) usage; exit 0 ;;
    :) usage >&2; die "option -$OPTARG needs an argument" 2 ;;
    \?) usage >&2; die "unknown option -$OPTARG" 2 ;;
  esac
done
shift $((OPTIND - 1))
[ "$#" -ge 1 ] || { usage >&2; die "need at least one INPUT" 2; }

# Temp dir and lock: both released by the EXIT trap, on success, error and signals.
TMP=$(mktemp -d "${TMPDIR:-/tmp}/${PROG%.sh}.XXXXXX")
LOCKDIR="${TMPDIR:-/tmp}/${PROG%.sh}.lock"
HAVE_LOCK=0
STAGED=""

cleanup() {
  local rc=$?                     # first line: remember the real exit status
  trap - EXIT INT TERM HUP        # no re-entry while cleaning up
  rm -rf "$TMP"
  if [ -n "$STAGED" ]; then rm -f "$STAGED"; fi
  if [ "$HAVE_LOCK" -eq 1 ]; then rmdir "$LOCKDIR" 2>/dev/null || true; fi
  [ "$rc" -eq 0 ] || log ERROR "exiting with status $rc"
  exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP

# mkdir is atomic on every POSIX filesystem: exactly one caller creates the directory.
if mkdir "$LOCKDIR" 2>/dev/null; then HAVE_LOCK=1; else die "another instance holds $LOCKDIR" 3; fi

# --- the actual work: count lines per input, atomically publish the report ---
report="$TMP/report.txt"
for f in "$@"; do
  [ -r "$f" ] || die "cannot read: $f" 4
  debug "counting $f"
  count=$(wc -l <"$f")            # its own assignment: under set -e a failure here aborts the script
  count=${count//[[:space:]]/}    # (BSD wc pads the number with spaces)
  printf '%s\t%s\n' "$count" "$f" >>"$report"
done

if [ -n "$OUTPUT" ]; then
  # Stage next to the destination: rename(2) is atomic only inside one filesystem; a mv from
  # $TMPDIR on another filesystem silently becomes copy-then-delete and readers can see half a file.
  if [ "$DRY_RUN" -eq 1 ]; then
    run mv "$(dirname "$OUTPUT")/.${PROG%.sh}.XXXXXX" "$OUTPUT"
    info "would write $OUTPUT"
  else
    STAGED=$(mktemp "$(dirname "$OUTPUT")/.${PROG%.sh}.XXXXXX")
    cat "$report" >"$STAGED"
    mv "$STAGED" "$OUTPUT"
    STAGED=""
    info "wrote $OUTPUT"
  fi
else
  cat "$report"
fi

Real output on the build host (bash 3.2.57; $TMPDIR abbreviates the per-user temp directory):

text
$ bash scripts/safe-template.sh -v data/orders.csv
2026-11-29T09:37:30Z DEBUG safe-template.sh: counting data/orders.csv
5	data/orders.csv
[exit 0]
$ bash scripts/safe-template.sh -n -o /tmp/out.txt data/orders.csv
DRY-RUN: mv /tmp/.safe-template.XXXXXX /tmp/out.txt
2026-11-29T09:56:48Z INFO  safe-template.sh: would write /tmp/out.txt
[exit 0]                                   # and /tmp/out.txt does not exist
$ bash scripts/safe-template.sh /nonexistent
2026-11-29T09:37:30Z ERROR safe-template.sh: cannot read: /nonexistent
2026-11-29T09:37:30Z ERROR safe-template.sh: exiting with status 4
[exit 4]
$ mkdir $TMPDIR/safe-template.lock; bash scripts/safe-template.sh data/orders.csv
2026-11-29T09:37:30Z ERROR safe-template.sh: another instance holds $TMPDIR/safe-template.lock
2026-11-29T09:37:30Z ERROR safe-template.sh: exiting with status 3
[exit 3]
$ SIGTERM while running                    # sent to the script; it exits after the blocked child ends
2026-11-29T09:37:33Z ERROR safe-template.sh: exiting with status 143
[exit 143]                                 # and no safe-template.* directory is left in $TMPDIR

Locks: flock, mkdir and why a PID file is not a lock Important ​

In plain words: a lock lets a script say "only one of me at a time". Cron starts a job every five minutes whether or not the last one finished, so a slow run overlaps the next and both corrupt shared state.

Common misunderstanding: "if [ -f job.pid ]; then exit; fi; echo $$ > job.pid is a lock." Between the test and the write another copy can pass the same test (a race), and a crash leaves a stale PID file that blocks every future run. A lock must be acquired atomically and released by the kernel when the process dies.

Definition: flock(1) (util-linux, Linux) "manages flock(2) locks from within shell scripts or from the command line" (man7). Forms: flock FILE command (wrap a command), flock -n FILE command (fail at once if busy), flock -w SECONDS ... (wait up to N seconds), and flock -n 9 on an open file descriptor from exec 9>file. By default, "if the lock cannot be immediately acquired, flock waits until the lock is available." The lock belongs to the open file description, so the kernel drops it when the process exits, even on kill -9. macOS has no flock command by default; the portable atomic primitive is mkdir (it either creates the directory or fails; clean it in the EXIT trap), at the price that a kill -9 leaves a stale directory.

bash
#!/usr/bin/env bash
# Lock with flock(1) (util-linux, Linux only; not installed on stock macOS).
# The lock belongs to the open file descriptor, so the kernel drops it when the
# process dies, even on SIGKILL: no stale lock file to clean up.
set -euo pipefail

LOCKFILE=${LOCKFILE:-/var/lock/nightly-report.lock}

exec 9>"$LOCKFILE"                       # open (create) the lock file on fd 9
if ! flock --nonblock 9; then            # -n: do not wait; fail at once
  echo "nightly-report: previous run still active, skipping" >&2
  exit 0                                  # for cron, "skipped" is not an error
fi

echo "holding the lock as pid $$"
sleep 2                                   # ... the real work ...

# Variants, as one-liners:
#   flock -n /var/lock/job.lock  command args      # wrap a command, skip if busy
#   flock -w 30 /var/lock/job.lock command args    # wait up to 30 seconds
#   flock -x 9 / flock -s 9                          # exclusive (default) or shared lock
MechanismAtomicSurvives kill -9 cleanlyPortableNotes
flock -n on an fdYesYes (kernel releases)Linux (util-linux); not stock macOSLocks are advisory: every contender must ask for the lock
mkdir lockdirYesNo (stale dir)EverywhereAdd an age check or PID inside for recovery
ln -s pid locknameYesNoEverywhereSame stale problem; the link target can hold the PID
[ -f pidfile ] then writeNoNoEverywhereRacy; do not use
set -o noclobber; echo > fileYes (O_EXCL)NoPOSIXWorks as a lock acquire
Database advisory lock (pg_advisory_lock)YesYes (session end)Needs a DBRight choice for multi-host jobs
Laravel --isolated, Cache::lockYes (cache driver lock)Depends on TTLLaravelA skipped isolated command still exits 0

Real scenario: the nightly report takes 70 minutes on bad days; a */5 cron wrapper takes the lock with flock -n and logs "skipped". For jobs that run on several hosts the lock must live where all hosts see it (a database or Redis lock), not in /var/lock on one host.

Idempotent scripts, dry-run flags and logging in scripts Must-know ​

In plain words: an idempotent script can be run twice and leaves the same result as running it once: it checks "is this already done?" before acting. A dry run prints what it would do and does nothing. Logging means timestamps and levels on stderr, and an exit status that tells the truth.

Common misunderstanding: "My script is idempotent because it doesn't fail the second time." Not failing is not enough: echo "export X=1" >> ~/.profile succeeds every time and appends a duplicate every time. And "dry-run means adding echo in front of everything": only if every mutation goes through one wrapper, otherwise some command is missed.

Definition: idempotent building blocks: mkdir -p, ln -sfn target link, rm -f, grep -qxF "$line" file || echo "$line" >> file, install -m 0644 src dest, cp -p, state files ("done" markers), writing the desired config and comparing (cmp -s) before replacing. Dry-run: a single run() function that prints DRY-RUN: cmd args (with printf ' %q' so spaces survive) or executes. Logging: log LEVEL msg to stderr with an ISO-8601 UTC timestamp so stdout stays data; -v for debug; never log secrets; exit statuses documented in usage.

1  $ deploy.sh 1.4.2 art/            # first run: unpack, migrate, switch symlink, restart
2  $ deploy.sh 1.4.2 art/            # second run
3  10:02:11 deploy: 1.4.2 is already current; nothing to do      # exit 0, nothing executed
4  $ deploy.sh --dry-run 1.5.0 art/
5  DRY-RUN: ln -sfn /srv/orders/releases/1.5.0 /srv/orders/current.new   # printed, not run
OperationNot idempotentIdempotent
Create directorymkdir d (fails on rerun)mkdir -p d
Symlinkln -s a b (error or nested link)ln -sfn a b
Add a lineecho x >> fgrep -qxF x f || echo x >> f
Install a filecp a binstall -m 0644 a b, or compare with cmp -s first
Create a databasecreatedb xpsql -tc "SELECT 1 FROM pg_database WHERE datname='x'" | grep -q 1 || createdb x
Create a useruseradd bobid bob || useradd bob
Migratecustom SQLthe framework's tracked migrations (artisan migrate)
Deploy a versionunpack and restartskip when readlink current equals the target

Argument parsing with getopts Important ​

In plain words: getopts is the built-in that reads -n -v -o file style options one at a time, so a script accepts flags in any order and rejects unknown ones.

Common misunderstanding: "getopts handles --long-options." It does not: it parses short options only. For long options write a case loop (as deploy.sh does for --dry-run) or use GNU getopt (not on stock macOS; the BSD getopt differs) or a real program.

Definition: while getopts ':nvo:h' opt; do case $opt in n) ...;; o) OUT=$OPTARG;; :) missing arg;; \?) unknown;; esac; done; shift $((OPTIND - 1)). A leading : in the option string selects silent mode: : is reported for a missing argument and ? for an unknown option, with the letter in OPTARG; o: means -o takes an argument in OPTARG; OPTIND is the index of the next argument, so after the loop shift $((OPTIND-1)) leaves the operands. -- ends option parsing.

StyleToolProsCons
Short flagsgetopts builtinPOSIX, portable, no external programNo long options, no option permutation
Hand-written casewhile [ $# -gt 0 ]Long options, easyYou handle -- and -abc yourself
GNU getoptutil-linux getoptLong options, permutationNot on stock macOS; quoting rules are subtle
Subcommandscase $1 in start) ... ;; stop) ... ;; esacGit-style CLIsPast ~100 lines, consider Go (cobra, flag)

The template above handles -n, -v, -o FILE, -h, a missing option argument (status 2) and an unknown option (status 2).

Environment variables, .env files and secrets Must-know ​

In plain words: environment variables are the settings every child process inherits. A .env file is a plain text list of KEY=VALUE lines used to set them in development. Secrets are environment variables that must not leak.

Common misunderstanding: "source .env is the standard way to load it." It executes the file as shell code: a value containing $(...) or a backtick runs a command, and PASSWORD=a b is parsed as a command b with PASSWORD=a in its environment. Also, "environment variables are private": any process of the same user can read /proc/PID/environ (Linux), and command-line arguments are visible to every user in the process list.

Definition: export VAR=value (copy into the environment of children), VAR=value cmd (for one command only), env -i (clean environment), printenv, : "${VAR:?msg}" (require). set -a; . file; set +a auto-exports everything a trusted file defines. For untrusted or merely data-like files parse line by line without eval (the loader below). Where secrets belong: a secret manager injected at runtime, a file with mode 0600 or a mounted secret (Docker/Kubernetes secrets, covered in the platform chapters), never in the repository, never as a command-line argument, never echoed by set -x.

bash
#!/usr/bin/env bash
# Load KEY=VALUE pairs from a .env file WITHOUT sourcing it as code, and keep secrets out
# of logs and the process list. `. .env` executes whatever the file contains.
set -euo pipefail

load_env() { # load_env FILE : export every KEY=VALUE line; ignore comments and blanks
  local file=$1 key value
  while IFS='=' read -r key value || [ -n "$key" ]; do
    case $key in ''|'#'*) continue ;; esac
    case $key in *[!A-Za-z0-9_]*) echo "bad key in $file: $key" >&2; return 1 ;; esac
    value=${value%\"}; value=${value#\"}            # strip one pair of double quotes
    export "$key=$value"                              # export takes a literal assignment
  done <"$file"
}

mask() { # show only the last 2 characters of a secret
  local v=$1; printf '%s\n' "****${v: -2}"
}

here=$(cd "$(dirname "$0")" && pwd)
load_env "$here/../data/env.example"
echo "APP_ENV=$APP_ENV DB_HOST=$DB_HOST DB_PORT=$DB_PORT GREETING=[$GREETING]"
echo "API_TOKEN=$(mask "$API_TOKEN")"

echo "--- required variables: fail early with a name, not later with a mystery"
( : "${MISSING_SETTING:?MISSING_SETTING is required}" ) 2>&1 || echo "status $?"

echo "--- secrets on the command line are visible to every user via ps; pass them on stdin or by file"
# curl -K - reads its options (here a header holding the token) from stdin, not from argv:
#   printf 'header = "Authorization: Bearer %s"\n' "$API_TOKEN" | curl -K - https://api.example.com/orders

echo "--- permissions: a .env file must not be world-readable"
tmp=$(mktemp); chmod 600 "$tmp"; ls -l "$tmp" | cut -c1-10; rm -f "$tmp"
text
APP_ENV=production DB_HOST=db.internal DB_PORT=5432 GREETING=[hello world]
API_TOKEN=****me
--- required variables: fail early with a name, not later with a mystery
scripts/dotenv.sh: line 26: MISSING_SETTING: MISSING_SETTING is required
status 1
--- permissions: a .env file must not be world-readable
-rw-------
PlaceVisible toPersistsUse for
Command-line argumentEvery user (ps) and shell historyLogs, historyNever for secrets
Environment variableSame user and root (/proc/PID/environ), child processesProcess lifetime; crash dumpsNon-secret config; secrets only with care (12-factor style)
File with mode 0600Owner and rootDiskSecrets on one host; curl -K file
stdin pipeThe two processesNowherecurl -K -, docker login --password-stdin
Secret manager / mounted secretAuthorised workloadsManagedProduction (Kubernetes Secrets, Vault, cloud secret stores)
Git repositoryEveryone with access, foreverHistoryNever; rotate if it happens

Real scenario: a CI job with set -x prints a token into the build log: mask it or turn tracing off around the call; a Dockerfile ENV TOKEN=... bakes a secret into an image layer (see Images & Dockerfiles); a Laravel .env committed by mistake. docker login --password-stdin, kubectl create secret generic --from-file, GitHub Actions secrets.X are the stdin/file/managed patterns.

shellcheck, shfmt and Bats testing Must-know ​

In plain words: shellcheck reads your script and warns about the classic mistakes; shfmt rewrites it into one consistent layout; Bats runs small test functions against your script.

Common misunderstanding: "Linting is style." shellcheck's top rules are correctness: SC2086 "Double quote to prevent globbing and word splitting", SC2046 (unquoted command substitution), SC2164 (cd without || exit), SC2155 (declare and assign separately), SC2012 (do not parse ls), SC2162 (read without -r mangles backslashes), SC2181 (check $? indirectly), SC2034 (unused variable). Fixing them removes real bugs.

Definition: shellcheck script.sh (exit 1 when findings exist; -s sh|bash|dash picks the dialect; -x follows sourced files; --severity=warning; a # shellcheck disable=SC2012 comment with a reason silences one finding). shfmt "formats shell programs": shfmt -d (diff, non-zero if different), -w (write), -i 2 (2-space indent), -ci (indent case), -l (list files that differ). Bats-core: @test "name" { run script args; [ "$status" -eq 0 ]; [[ "$output" == *"x"* ]] }, with setup/teardown, $BATS_TEST_TMPDIR, run --separate-stderr (needs bats_require_minimum_version 1.5.0), and bats --recursive tests/.

bash
#!/usr/bin/env bats
# Bats-core tests for scripts/safe-template.sh. Bats is not installed in the build
# environment, so this file is "expected, not run"; tests/deploy-test.sh is the same
# idea in plain bash and was run.
# Install: brew install bats-core   |   apt-get install bats   |   npm install -g bats

bats_require_minimum_version 1.5.0   # run --separate-stderr needs it; silences the warning otherwise

setup() {
  SCRIPT="$BATS_TEST_DIRNAME/../scripts/safe-template.sh"
  DATA="$BATS_TEST_DIRNAME/../data"
  export TMPDIR="$BATS_TEST_TMPDIR"   # each test gets its own temp dir, removed by Bats
}

@test "no arguments: usage error, status 2" {
  run "$SCRIPT"
  [ "$status" -eq 2 ]
  [[ "$output" == *"need at least one INPUT"* ]]
}

@test "counts lines per input" {
  run --separate-stderr "$SCRIPT" "$DATA/orders.csv"
  [ "$status" -eq 0 ]
  [[ "$output" == 5*orders.csv ]]
}

@test "unreadable input: status 4 and the temp dir is gone" {
  run "$SCRIPT" /nonexistent
  [ "$status" -eq 4 ]
  run bash -c 'ls "$TMPDIR" | grep -c "^safe-template"'
  [ "$output" = "0" ]
}

@test "a held lock: status 3" {
  mkdir "$TMPDIR/safe-template.lock"
  run "$SCRIPT" "$DATA/orders.csv"
  [ "$status" -eq 3 ]
}

@test "dry run does not create the output file" {
  run "$SCRIPT" -n -o "$TMPDIR/out.txt" "$DATA/orders.csv"
  [ "$status" -eq 0 ]
  [ ! -e "$TMPDIR/out.txt" ]
}

@test "an input that is readable but cannot be counted fails and publishes nothing" {
  mkdir "$TMPDIR/out"
  run "$SCRIPT" -o "$TMPDIR/out/r.txt" "$TMPDIR"      # a directory: -r is true, wc -l fails
  [ "$status" -ne 0 ]
  [ -z "$(ls -A "$TMPDIR/out")" ]
}
bash
#!/usr/bin/env bash
# Offline test of deploy.sh: php, systemctl and curl are stubs on PATH that append to a
# call log, so the real script runs end to end in a scratch directory. No Bats needed.
set -euo pipefail
here=$(cd "$(dirname "$0")/.." && pwd)
work=$(mktemp -d "${TMPDIR:-/tmp}/deploy-test.XXXXXX")
trap 'rm -rf "$work"' EXIT

mkdir -p "$work/bin" "$work/art/laravel" "$work/root"
printf '#!/bin/sh\necho v\n' >"$work/art/orders-api"; chmod +x "$work/art/orders-api"
touch "$work/art/laravel/artisan"
for cmd in php systemctl; do
  printf '#!/bin/sh\necho "%s $*" >>"%s/calls.log"\nexit "${%s_RC:-0}"\n' "$cmd" "$work" "$cmd" >"$work/bin/$cmd"; chmod +x "$work/bin/$cmd"
done
printf '#!/bin/sh\necho "curl $*" >>"%s/calls.log"\nexit "${CURL_RC:-0}"\n' "$work" >"$work/bin/curl"; chmod +x "$work/bin/curl"

export PATH="$work/bin:$PATH" DEPLOY_ROOT="$work/root"
fail=0
check() { if "$@"; then echo "ok   - $DESC"; else echo "FAIL - $DESC"; fail=1; fi; }

DESC="first deploy creates the release and points current at it"
bash "$here/scripts/deploy.sh" 1.0.0 "$work/art" 2>/dev/null
check test "$(readlink "$work/root/current")" = "$work/root/releases/1.0.0"

DESC="second run of the same version is a no-op (idempotent)"
: >"$work/calls.log"
bash "$here/scripts/deploy.sh" 1.0.0 "$work/art" 2>/dev/null
check test ! -s "$work/calls.log"

DESC="a new version switches the symlink"
bash "$here/scripts/deploy.sh" 1.1.0 "$work/art" 2>/dev/null
check test "$(readlink "$work/root/current")" = "$work/root/releases/1.1.0"

DESC="failed health check rolls back and exits 5"
set +e; CURL_RC=22 bash "$here/scripts/deploy.sh" 1.2.0 "$work/art" 2>/dev/null; rc=$?; set -e
check test "$rc" = 5
DESC="... and current still points at 1.1.0"
check test "$(readlink "$work/root/current")" = "$work/root/releases/1.1.0"

DESC="failed service restart rolls back and exits 6"
set +e; systemctl_RC=1 bash "$here/scripts/deploy.sh" 1.3.0 "$work/art" 2>/dev/null; rc=$?; set -e
check test "$rc" = 6
DESC="... current is back on 1.1.0, so a retry is not mistaken for 'already deployed'"
check test "$(readlink "$work/root/current")" = "$work/root/releases/1.1.0"
DESC="the retry with a working restart deploys 1.3.0"
bash "$here/scripts/deploy.sh" 1.3.0 "$work/art" 2>/dev/null
check test "$(readlink "$work/root/current")" = "$work/root/releases/1.3.0"

DESC="dry run of a NEW Laravel release still reports migrate and optimize"
check sh -c "bash '$here/scripts/deploy.sh' --dry-run 4.0.0 '$work/art' 2>&1 | grep -q 'artisan migrate'"

DESC="a version with a slash is rejected (exit 2)"
set +e; bash "$here/scripts/deploy.sh" ../evil "$work/art" 2>/dev/null; rc=$?; set -e
check test "$rc" = 2

DESC="--dry-run changes nothing"
bash "$here/scripts/deploy.sh" --dry-run 9.9.9 "$work/art" 2>/dev/null
check test ! -e "$work/root/releases/9.9.9"

exit "$fail"
text
ok   - first deploy creates the release and points current at it
ok   - second run of the same version is a no-op (idempotent)
ok   - a new version switches the symlink
ok   - failed health check rolls back and exits 5
ok   - ... and current still points at 1.1.0
ok   - failed service restart rolls back and exits 6
ok   - ... current is back on 1.1.0, so a retry is not mistaken for 'already deployed'
ok   - the retry with a working restart deploys 1.3.0
ok   - dry run of a NEW Laravel release still reports migrate and optimize
ok   - a version with a slash is rejected (exit 2)
ok   - --dry-run changes nothing
bash
#!/usr/bin/env bash
# Plain-bash tests for scripts/safe-template.sh (the same cases as safe-template.bats).
set -euo pipefail
here=$(cd "$(dirname "$0")/.." && pwd)
work=$(mktemp -d "${TMPDIR:-/tmp}/st-test.XXXXXX"); trap 'rm -rf "$work"' EXIT
export TMPDIR="$work"; mkdir "$work/out"
fail=0
check() { if "$@"; then echo "ok   - $DESC"; else echo "FAIL - $DESC"; fail=1; fi; }
st() { bash "$here/scripts/safe-template.sh" "$@"; }

DESC="no arguments: status 2"
set +e; st >/dev/null 2>&1; rc=$?; set -e; check test "$rc" = 2
DESC="missing input: status 4"
set +e; st /nonexistent >/dev/null 2>&1; rc=$?; set -e; check test "$rc" = 4
DESC="a readable input that cannot be counted (a directory) fails and publishes nothing"
set +e; st -o "$work/out/r.txt" "$work" >/dev/null 2>&1; rc=$?; set -e
check test "$rc" -ne 0; DESC="... no output file and no staged leftovers"; check test -z "$(ls -A "$work/out")"
DESC="success writes the report next to the destination"
st -o "$work/out/r.txt" "$here/data/orders.csv" 2>/dev/null; check test "$(cut -f1 "$work/out/r.txt")" = 5
DESC="no staging file is left in the destination directory"; check test "$(ls -A "$work/out")" = r.txt
DESC="dry run creates nothing"
rm "$work/out/r.txt"; st -n -o "$work/out/r.txt" "$here/data/orders.csv" 2>/dev/null; check test -z "$(ls -A "$work/out")"
DESC="a held lock: status 3"
mkdir "$work/safe-template.lock"; set +e; st "$here/data/orders.csv" >/dev/null 2>&1; rc=$?; set -e; check test "$rc" = 3
exit "$fail"

tests/safe-template-test.sh runs the same five cases as the Bats file, plus the one a review found missing: a readable input that cannot be counted (a directory) must fail and publish nothing. It prints eight ok lines on the build host.

Build-environment honesty: shellcheck, shfmt, bats and yq are not installed on the build host, so the .bats file and the CI job below are "expected, not run". What was run instead: bash -n (syntax check) on every script, sh -n on the POSIX one, and tests/deploy-test.sh and tests/safe-template-test.sh, the same idea as Bats written in plain bash with stub programs on PATH (php, systemctl, curl).

yaml
# GitHub Actions job: lint, format-check and test every shell script on each push.
# shellcheck and shfmt are single static binaries; bats-core is a shell script.
name: shell-quality
on:
  pull_request:
    paths: ["**/*.sh", "tests/**", ".github/workflows/shell-quality.yml"]
permissions:
  contents: read
jobs:
  shell:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - name: Install tools (shellcheck is preinstalled on ubuntu-latest runners)
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends shfmt bats
      - name: shellcheck (warnings fail the job)
        run: git ls-files '*.sh' | xargs shellcheck --severity=style --external-sources
      - name: shfmt (-d prints a diff and exits non-zero when formatting differs)
        run: git ls-files '*.sh' | xargs shfmt -d -i 2 -ci
      - name: bats
        run: bats --recursive tests/

Where the tools sit in a pipeline: a pre-commit hook or a GitHub Actions job (above) or a GitLab CI job (shellcheck from the koalaman/shellcheck-alpine image) for lint; the same commands locally via make lint; Bats for scripts with logic. Docker image builds can lint Dockerfiles with hadolint, which runs ShellCheck over RUN instructions (see Images & Dockerfiles).

cron-safe scripts Important ​

In plain words: cron runs your script with almost nothing set up: no login shell, a tiny PATH, a different working directory. A cron-safe script sets up what it needs and prints only when something is wrong.

Common misunderstanding: "It works in my terminal, so it works in cron." The crontab(5) man page: "SHELL is set to /bin/sh, and LOGNAME and HOME are set from the /etc/passwd line of the crontab's owner." There is no profile, no ~/.bashrc, and PATH is typically /usr/bin:/bin. And the percent sign: "A % character ... will be changed into newline characters" unless escaped, which breaks date +%F.

Definition: set SHELL= and PATH= at the top of the crontab; use absolute paths for scripts and tools; cd explicitly; wrap the job in a script that locks, logs and exits with the real status; escape % as \% in the crontab line; send output where it will be seen (cron mails stdout and stderr to MAILTO unless redirected). systemd timers (see Linux for Developers) fix several of these: journald logs, Persistent=true catch-up, resource limits. Kubernetes CronJob has concurrencyPolicy: Forbid|Replace|Allow for the overlap problem.

bash
# Cron runs commands with a tiny environment: PATH=/usr/bin:/bin, no login shell, no
# profile, HOME set, cwd = $HOME. Set what you need here, not inside your head.
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin
MAILTO=ops@example.com

# m  h  dom mon dow  command
# Every 5 minutes: the wrapper takes a lock (no overlap), logs with a timestamp, never prints on success.
*/5 *  *   *   *    /opt/orders/bin/cron-wrapper.sh nightly-sync   /opt/orders/bin/sync.sh

# Laravel needs ONE cron entry, every minute; the scheduler itself decides which tasks are due:
*   *  *   *   *    cd /srv/orders/current && /usr/bin/php artisan schedule:run >> /dev/null 2>&1

# Percent signs are special in crontab (they mean newline); escape them: date +\%F
30  3  *   *   *    /usr/bin/tar -czf /backup/orders-$(date +\%F).tgz /srv/orders/shared
bash
#!/usr/bin/env bash
# cron-wrapper.sh NAME COMMAND [ARGS...]
# Makes any command safe under cron: absolute PATH, own lock (no overlapping runs),
# timestamped log file, output only on failure (so MAILTO mails mean something), and the
# command's real exit status. Uses flock when present (Linux), else the portable mkdir lock.
set -euo pipefail
PATH=/usr/local/bin:/usr/bin:/bin:$PATH
[ "$#" -ge 2 ] || { echo "usage: ${0##*/} NAME COMMAND [ARGS...]" >&2; exit 2; }
name=$1; shift

state=${STATE_DIR:-${TMPDIR:-/tmp}/cron-$name}
mkdir -p "$state"
log="$state/last.log"

if command -v flock >/dev/null 2>&1; then
  exec 9>"$state/lock"
  flock -n 9 || { echo "$name: still running, skipped" >>"$state/skipped.log"; exit 0; }
else
  mkdir "$state/lock.d" 2>/dev/null || { echo "$name: still running, skipped" >>"$state/skipped.log"; exit 0; }
  trap 'rmdir "$state/lock.d"' EXIT
fi

start=$(date +%s)
set +e
{ printf '%s start %s\n' "$(date -u +%FT%TZ)" "$name"; "$@"; } >"$log" 2>&1
rc=$?
set -e
printf '%s end   %s rc=%d seconds=%d\n' "$(date -u +%FT%TZ)" "$name" "$rc" "$(( $(date +%s) - start ))" >>"$log"

if [ "$rc" -ne 0 ]; then
  cat "$log" >&2            # cron mails stderr/stdout: only failures are noisy
fi
exit "$rc"
text
$ cron-wrapper.sh demo sh -c "echo working; sleep 1"          # exit 0; last.log holds the run
start demo
working
end   demo rc=0 seconds=1
$ (a second copy started while the first is still running)    # exit 0; skipped.log gets one line
demo: still running, skipped
$ cron-wrapper.sh demo sh -c "echo boom; exit 7"              # the failure is printed (cron would mail it) and propagated
start demo
boom
end   demo rc=7 seconds=0
[exit 7]

(mkdir lock branch, because stock macOS has no flock; timestamps trimmed. On Linux the flock -n 9 branch is taken: expected, not run.)

Cron trapSymptomFix
Minimal PATHcommand not found only under cronPATH= line in the crontab; absolute paths
% in the commandThe command is truncated at the first %Escape as \% or move it into a script
Overlapping runsCorrupt data, load spikesLock (flock -n), or */5 jobs that take 7 minutes
No output captured"It ran?"Wrapper writes a log with start, end, status
Noisy success mailEveryone filters cron mailPrint only on failure
Different HOME, cwdFiles created in $HOMEcd to the right place
Time zone and DSTJob skipped or run twiceRun in UTC, or use a timer with OnCalendar
Laravel tasksEvery task has its own cron lineOne line: * * * * * cd /srv/orders/current && php artisan schedule:run

Portability: macOS BSD tools vs GNU Important ​

In plain words: Linux ships GNU versions of the Unix tools and macOS ships BSD versions. Most flags agree; the ones that do not are the ones that bite: sed -i, date -d, grep -P, readlink -f, xargs -r, stat -c.

Common misunderstanding: "A script tested on my Mac works on the CI runner." The reverse is equally true. The fixes are: install GNU tools on the Mac (brew install coreutils gnu-sed gawk grep, then call gsed, gawk... or put $(brew --prefix)/opt/<tool>/libexec/gnubin first in PATH), test in a Linux container, or write to the common subset.

Definition of "the common subset": POSIX utilities and flags; sed -E not -r; sed -i.bak ... && rm f.bak; grep -E not -P; date -u +%FT%TZ for timestamps (and do date arithmetic in awk or Go); mktemp -d "${TMPDIR:-/tmp}/x.XXXXXX"; printf not echo -e; command -v not which; find ... -print0 | xargs -0 and -exec ... +.

bash
#!/usr/bin/env bash
# macOS (BSD) versus Linux (GNU) differences that break scripts. Run on macOS here;
# the GNU column is "expected, not run".
set -u
tmp=$(mktemp "${TMPDIR:-/tmp}/port.XXXXXX"); trap 'rm -f "$tmp" "$tmp.bak"' EXIT
printf 'hello world\n' >"$tmp"

echo "--- sed -i: GNU takes an optional suffix glued to -i; BSD requires a separate (maybe empty) argument"
sed -i 's/hello/bye/' "$tmp" 2>&1 | head -1              # GNU: works.  BSD: error, treats the script as the suffix
sed -i '' 's/hello/bye/' "$tmp" 2>&1 | head -1           # BSD: works.   GNU: error ("can't read s/hello/bye/")
echo "portable form: sed -i.bak 's/x/y/' file && rm file.bak"
printf 'hello world\n' >"$tmp"; sed -i.bak 's/hello/hi/' "$tmp"; cat "$tmp"

echo "--- sed escapes: \\t and \\+ in patterns are GNU extensions in POSIX terms; recent macOS accepts \\t, older BSDs do not"
printf 'a b\n' | sed 's/ /\t/' | od -c | head -1             # GNU and macOS 15: a tab; strict POSIX sed: a literal t
printf 'a b\n' | sed 's/ /\
/'                                                           # portable newline: backslash + real newline

echo "--- grep -P (PCRE) is GNU only"
echo 'order-42' | grep -oP '\d+' 2>&1 | head -1              # BSD grep: usage error. Use grep -Eo '[0-9]+'
echo 'order-42' | grep -Eo '[0-9]+'

echo "--- date: GNU -d versus BSD -j -f / -v"
date -d '2026-11-29 +1 day' +%F 2>&1 | head -1               # GNU only
date -j -v+1d -f '%Y-%m-%d' '2026-11-29' +%F 2>&1 | head -1  # BSD only

echo "--- GNU-only or newer-BSD-only: readlink -f (macOS 12.3+), sort -V, xargs -r, stat -c, find -printf"
readlink -f . 2>&1 | head -1
xargs -r echo x </dev/null 2>&1 | head -1                    # GNU: no output. BSD: ok but runs echo once on some versions

echo "--- shell versions"
echo "bash=$BASH_VERSION"; echo "associative arrays need bash 4:"
bash -c 'declare -A m; m[a]=1; echo "map ok: ${m[a]}"' 2>&1 | head -1
bash -c 'x=Hello; echo "${x,,}"' 2>&1 | head -1
bash -c 'mapfile -t a < /dev/null; echo mapfile ok' 2>&1 | head -1
text
--- sed -i: GNU takes an optional suffix glued to -i; BSD requires a separate (maybe empty) argument
sed: 1: "/var/folders/kr/ckwpc60 ...": invalid command code f
--- grep -P (PCRE) is GNU only
grep: invalid option -- P
42
--- date: GNU -d versus BSD -j -f / -v
date: illegal option -- d
2026-11-30
--- shell versions
bash=3.2.57(1)-release
associative arrays need bash 4:
bash: line 0: declare: -A: invalid option
bash: ${x,,}: bad substitution
bash: mapfile: command not found
ToolGNU (Linux)BSD (macOS)Portable choice
sed -i-i[SUFFIX]-i SUFFIX (empty string allowed as separate arg)-i.bak then rm
sed ERE-E or -r-E-E
grep -PPCRENot availablegrep -E, or perl -ne
date arithmeticdate -d '+1 day'date -v+1dCompute in awk/Go; date -u +%s works in both
readlink -fYesRecent macOS (worked on the build host); older releases: nocd "$(dirname "$0")" && pwd
xargsruns once on empty input unless -rnever runs on empty input; accepts -r, -P, -0-0 and -r
stat-c %s-f %zwc -c < file
sort -V, -hYesRecent macOS onlyAvoid or test
echo -eShell-dependentPrints -e under shprintf
awkgawk or mawkone-true-awk 20200816POSIX awk subset
bash5.x3.2.57No declare -A, mapfile, ${x,,}, |&, &>>

Real scenario: a CI step that uses sed -i 's/x/y/' f works on Ubuntu runners and fails on a developer's Mac; a Dockerfile RUN using sort -V works on Debian and fails on Alpine's BusyBox sort in older images; a Makefile with [[ ]] fails because make uses /bin/sh.

When to switch to Go or Python Must-know ​

In plain words: shell is glue. When the script stops being glue and starts being logic, rewrite it as a program before it grows.

Common misunderstanding: "I'll rewrite it later when it hurts." The Google Shell Style Guide says: "If you are writing a script that is more than 100 lines long, or that uses non-straightforward control flow logic, you should rewrite it in a more structured language now. Bear in mind that scripts grow. Rewrite your script early to avoid a more time-consuming rewrite at a later date." Its other rules: shell "is acceptable" when you are "mostly calling other utilities and are doing relatively little data manipulation", and "If performance matters, use something other than shell."

SignalStay in shellMove to GoMove to Python
Mostly starting programs and pipingYes
Under about 100 lines, one authorYes
Data structures, maps of records, sorting by several keysYesYes
Retries with backoff, timeouts, concurrencyxargs -P for simple fan-outYes (goroutines, context)Yes (asyncio)
Parsing CSV with quoted fields, XML, dates and time zonesYesYes
Needs unit tests, mocks, a stable APIBats for small scriptsYesYes
Ships to users (no shell guaranteed, Windows)Yes (one static binary)Possible
Long-running service or controllerYesYes
Ad-hoc data analysis, plottingYes
In a distroless or scratch containerNot possible (no shell)YesYes

A middle path is the Go binary wrapper: keep the shell script as a thin launcher (load config, validate, exec the binary) and put the logic in Go; or keep shell stages in a pipeline and replace one stage with a Go filter that reads stdin and writes stdout (the logsummary command below).

Mechanics ​

How the shell runs one command line ​

1  line:   grep -E ' 5[0-9]{2} ' "$LOG" | sort | uniq -c > counts.txt 2> err.txt
2  parse:  tokens -> pipeline of 3 simple commands + redirections (quotes are tracked here)
3  expand: brace -> tilde -> $var / $(cmd) / $((n)) -> word splitting -> globbing -> quote removal
4  pipe:   pipe(2) x2 ; fork() x3 (stages run concurrently, each in its own process)
5  child:  dup2() the pipe ends and redirections onto fds 0,1,2 ; execve("/usr/bin/grep", argv, envp)
6  parent: wait() for all children ; $? = status of the last (or the last non-zero with pipefail)
7  note:   builtins (cd, export, read) must run in the shell itself, so in a pipeline they run in a subshell

Consequences you can derive from the sequence: cd or an assignment inside a pipeline stage is lost (step 7); redirection files are opened before the command starts (so sort f > f empties f); expansion happens before exec, so the program never sees the quotes or the variable names, only the final words; execve replaces the process image, which is why exec cmd in a script makes the command the process that receives signals.

Expansion order, precisely ​

The Bash manual defines the order: brace expansion; tilde expansion; parameter and variable expansion, arithmetic expansion and command substitution (left to right); word splitting; filename expansion; quote removal. POSIX sh has no brace expansion. Word splitting applies only to the results of unquoted expansions, never to literal text; filename expansion applies to any word with an unquoted glob character, so a literal data/*.csv is expanded too (the manual lists splitting before filename expansion, and the results of filename expansion are not split again). And [[ ]] operands are exempt ("The words between the [[ and ]] do not undergo word splitting", Bash manual).

The knobs ​

KnobWhereEffectDefault / note
set -e, -u, -o pipefailScriptStrict mode (see above)Off
set -x, PS4='+ ${BASH_SOURCE}:${LINENO}: 'Script or bash -xTrace with file and linePS4 is + ; secrets are printed
set -f / set +fScriptDisable / enable globbingEnabled
shopt -s nullglobbashAn unmatched glob expands to nothingOff: the glob stays literal
shopt -s failglobbashAn unmatched glob is an errorOff
shopt -s globstarbash 4** matches directories recursivelyOff
shopt -s inherit_errexitbash 4.4$(...) inherits set -eOff: x=$(false; echo hi) continues inside the substitution
IFSAnyCharacters for word splitting and readSpace, tab, newline
LC_ALL=CEnvironmentByte-wise sort and character classes; much faster grep, deterministic sortLocale dependent
TMPDIREnvironmentWhere mktemp creates files/tmp
PATHEnvironmentWhere commands are looked upMinimal under cron and in Docker RUN
BASH_ENVEnvironmentFile sourced by non-interactive bashUnset; a hidden startup file in CI
umask 077ScriptNew files private to the owner022 typical
ulimit -nScriptOpen file descriptor limitSystem dependent; raise it for scripts that open many files
timeout 30 cmdcoreutils (gtimeout via Homebrew on macOS)Kill a command after N seconds, exit 124Not installed on stock macOS

Signals and exit statuses ​

SignalNumberTypical causeIn a script
SIGINT2Ctrl-Ctrap 'exit 130' INT so cleanup runs
SIGTERM15kill PID, docker stop, Kubernetes pod termination, systemd stoptrap 'exit 143' TERM
SIGHUP1Terminal closedOften treat like TERM
SIGKILL9kill -9, OOM killerCannot be trapped; cleanup never runs
SIGPIPE13Writing to a pipe whose reader exited (head)The writer dies with 141; trap '' PIPE ignores it
SIGCHLD17 / 20A child endedwait handles it; rarely trapped
ERR (pseudo)n/aA command failed under the -e rulestrap 'echo "line $LINENO" >&2' ERR with set -E
EXIT (pseudo)n/aAny exit of the shellThe cleanup hook

A container makes this concrete: Docker and Kubernetes deliver SIGTERM to PID 1. If PID 1 is a shell script that starts the real program without exec, the shell receives SIGTERM, does not forward it and the program is killed with SIGKILL after the grace period (Docker's stop timeout is 10 seconds for Linux containers; a Kubernetes Pod's grace period defaults to 30 seconds); the details and tini are in Images & Dockerfiles and the Go side in OS Processes, Signals & Graceful Shutdown.

Error messages you will actually see ​

MessageCauseFix
bash: TYPO_DIR: unbound variableset -u and a typo or an unset inputDefine it, or ${TYPO_DIR:-} when empty is valid
[: =: unary operator expected[ $empty = x ] with an unquoted empty variableQuote, or use [[ ]]
[: abc: integer expression expected-gt on a non-number (status 2)Validate input; use case $x in ''|*[!0-9]*)
bad substitution${x,,} or ${a[@]} in a shell that lacks it (bash 3.2, dash)Use a portable form or a newer bash
declare: -A: invalid optionAssociative array on bash < 4brew install bash, or use awk
mapfile: command not foundbash < 4while IFS= read -r loop
Syntax error: "(" unexpectedArray or [[ run by dashUse bash, or write POSIX
line 3: $'\r': command not found or /bin/bash^M: bad interpreterWindows CRLF line endings in the scriptsed -i.bak 's/\r$//' f; .gitattributes with *.sh text eol=lf
Permission denied (status 126)Script not executablechmod +x
command not found (status 127)Not in PATH (cron!), or a typoAbsolute path, set PATH
No such file or directory on a script that existsThe interpreter in the shebang is missing (#!/bin/bash on Alpine)Install bash or use #!/bin/sh
xargs: argument line too longMore arguments than ARG_MAXxargs -n / find -exec ... +
syntax error near unexpected tokenUnbalanced quote or missing fi / donebash -n script.sh, shellcheck
sed: 1: "...": invalid command code f (BSD)GNU-style sed -i 's/..//' filesed -i.bak

Go ​

A Go program is the right next step when a pipeline needs types, tests or a single deployable binary. Two small programs here show it: the log summary that the awk one-liners compute, and a safe way to start external programs.

Before ​

The awk version (also in scripts/text-pipeline.sh; real output in the lab):

bash
awk '{ split($7, p, "?"); s[p[1]] += $NF; n[p[1]]++; if ($NF > m[p[1]]) m[p[1]] = $NF }
     END { for (k in s) printf "%-16s n=%d avg=%.3f max=%.3f\n", k, n[k], s[k]/n[k], m[k] }' access.txt | sort

It is eight fields of positional knowledge ($7, $NF), no error handling for a half-written line and no test. It is also fine for a one-off.

After ​

go
// Package logsummary is the Go twin of the awk one-liners in scripts/text-pipeline.sh:
// the same access-log format, the same aggregates, but typed, testable and fast.
package logsummary

import (
	"bufio"
	"fmt"
	"io"
	"sort"
	"strconv"
	"strings"
)

// PathStats aggregates the requests for one path (query string removed).
type PathStats struct {
	Path    string
	Count   int
	Seconds float64 // sum of request times
	Max     float64
}

// Avg is the mean request time in seconds.
func (p PathStats) Avg() float64 { return p.Seconds / float64(p.Count) }

// Summary is what the awk script prints, as data.
type Summary struct {
	Total   int
	Classes map[string]int // "2xx", "4xx", "5xx"
	Paths   []PathStats    // sorted by Path
	Bad     int            // lines that did not parse
}

// ErrorRatio is the share of 5xx responses, 0..1.
func (s Summary) ErrorRatio() float64 {
	if s.Total == 0 {
		return 0
	}
	return float64(s.Classes["5xx"]) / float64(s.Total)
}

// Parse reads `ip - - [time] "METHOD path proto" status bytes seconds` lines.
// Malformed lines are counted, not fatal: a log tail can hold a half-written line.
func Parse(r io.Reader) (Summary, error) {
	s := Summary{Classes: map[string]int{}}
	byPath := map[string]*PathStats{}

	sc := bufio.NewScanner(r)
	sc.Buffer(make([]byte, 64*1024), 1024*1024) // default 64 KiB token limit is too small for some logs
	for sc.Scan() {
		f := strings.Fields(sc.Text())
		// awk's $6..$9 and $NF: method is "GET (with quote), path, proto, status, bytes, seconds
		if len(f) < 11 {
			s.Bad++
			continue
		}
		status, err1 := strconv.Atoi(f[8])
		secs, err2 := strconv.ParseFloat(f[len(f)-1], 64)
		if err1 != nil || err2 != nil {
			s.Bad++
			continue
		}
		path, _, _ := strings.Cut(f[6], "?")
		s.Total++
		s.Classes[fmt.Sprintf("%dxx", status/100)]++

		p := byPath[path]
		if p == nil {
			p = &PathStats{Path: path}
			byPath[path] = p
		}
		p.Count++
		p.Seconds += secs
		if secs > p.Max {
			p.Max = secs
		}
	}
	if err := sc.Err(); err != nil {
		return s, fmt.Errorf("reading log: %w", err)
	}
	for _, p := range byPath {
		s.Paths = append(s.Paths, *p)
	}
	sort.Slice(s.Paths, func(i, j int) bool { return s.Paths[i].Path < s.Paths[j].Path })
	return s, nil
}
go
package logsummary

import (
	"math"
	"os"
	"strings"
	"testing"
)

func TestParseMatchesTheAwkOutput(t *testing.T) {
	f, err := os.Open("../../data/access.txt")
	if err != nil {
		t.Fatal(err)
	}
	defer f.Close()

	s, err := Parse(f)
	if err != nil {
		t.Fatal(err)
	}
	// The numbers the awk pipelines print in the chapter's lab.
	if s.Total != 12 || s.Bad != 0 {
		t.Fatalf("total=%d bad=%d, want 12 and 0", s.Total, s.Bad)
	}
	want := map[string]int{"2xx": 9, "4xx": 1, "5xx": 2}
	for k, v := range want {
		if s.Classes[k] != v {
			t.Errorf("class %s = %d, want %d", k, s.Classes[k], v)
		}
	}
	if got := math.Round(s.ErrorRatio()*1000) / 10; got != 16.7 {
		t.Errorf("error ratio = %v%%, want 16.7%%", got)
	}
	var orders PathStats
	for _, p := range s.Paths {
		if p.Path == "/orders" {
			orders = p
		}
	}
	if orders.Count != 3 || math.Abs(orders.Avg()-0.487) > 0.0005 || orders.Max != 1.002 {
		t.Errorf("/orders = %+v (avg %.3f)", orders, orders.Avg())
	}
	if len(s.Paths) != 6 {
		t.Errorf("paths = %d, want 6 (query string stripped)", len(s.Paths))
	}
}

func TestMalformedLinesAreCounted(t *testing.T) {
	in := "garbage\n" +
		`1.2.3.4 - - [x +0000] "GET /a HTTP/1.1" notanumber 1 0.1` + "\n" +
		`1.2.3.4 - - [x +0000] "GET /a HTTP/1.1" 200 1 0.1` + "\n"
	s, err := Parse(strings.NewReader(in))
	if err != nil {
		t.Fatal(err)
	}
	if s.Total != 1 || s.Bad != 2 {
		t.Fatalf("total=%d bad=%d, want 1 and 2", s.Total, s.Bad)
	}
}

func TestEmptyInput(t *testing.T) {
	s, err := Parse(strings.NewReader(""))
	if err != nil || s.Total != 0 || s.ErrorRatio() != 0 {
		t.Fatalf("got %+v, %v", s, err)
	}
}
go
// Command logsummary reads an access log (stdin or a file argument) and prints the
// same report as the awk pipeline. Exit status: 0 ok, 1 read error, 2 usage error,
// 3 error ratio above -max-error (so a cron job or CI step can fail on it).
package main

import (
	"flag"
	"fmt"
	"io"
	"os"

	"academy/shell-scripting-text-processing/logsummary"
)

func main() { os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr)) }

func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
	fs := flag.NewFlagSet("logsummary", flag.ContinueOnError)
	fs.SetOutput(stderr)
	maxErr := fs.Float64("max-error", 1.0, "fail (exit 3) when the 5xx ratio exceeds this value (0..1)")
	if err := fs.Parse(args); err != nil {
		return 2
	}

	in := stdin
	if fs.NArg() > 1 {
		fmt.Fprintln(stderr, "usage: logsummary [-max-error R] [FILE]")
		return 2
	}
	if fs.NArg() == 1 {
		f, err := os.Open(fs.Arg(0))
		if err != nil {
			fmt.Fprintln(stderr, "logsummary:", err)
			return 1
		}
		defer f.Close()
		in = f
	}

	s, err := logsummary.Parse(in)
	if err != nil {
		fmt.Fprintln(stderr, "logsummary:", err)
		return 1
	}
	for _, c := range []string{"2xx", "3xx", "4xx", "5xx"} {
		if n := s.Classes[c]; n > 0 {
			fmt.Fprintf(stdout, "%s %d\n", c, n)
		}
	}
	for _, p := range s.Paths {
		fmt.Fprintf(stdout, "%-16s n=%d avg=%.3f max=%.3f\n", p.Path, p.Count, p.Avg(), p.Max)
	}
	fmt.Fprintf(stdout, "%d of %d = %.1f%%\n", s.Classes["5xx"], s.Total, 100*s.ErrorRatio())
	if s.ErrorRatio() > *maxErr {
		return 3
	}
	return 0
}
go
// Package runcmd runs an external program the way a careful shell script would, minus
// the shell: arguments are passed as a vector (no word splitting, no globbing, no
// injection), the child gets a deadline, and the exit status is a value, not a guess.
package runcmd

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"os/exec"
	"time"
)

// Result is what a script reads from $?, stdout and stderr.
type Result struct {
	Stdout   string
	Stderr   string
	ExitCode int // -1 when the process did not start or was killed by a signal
}

// ErrTimeout is returned when the deadline killed the child.
var ErrTimeout = errors.New("command timed out")

// Run executes name with args and a timeout. It never invokes a shell.
// When the context ends, exec.CommandContext kills the child (the default Cancel is
// Process.Kill). WaitDelay (added in Go 1.20) then bounds how long Wait may block on
// the output pipes, so a grandchild that keeps stdout open cannot hang the caller.
func Run(ctx context.Context, timeout time.Duration, name string, args ...string) (Result, error) {
	ctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()

	cmd := exec.CommandContext(ctx, name, args...)
	var out, errb bytes.Buffer
	cmd.Stdout, cmd.Stderr = &out, &errb
	cmd.WaitDelay = 2 * time.Second

	err := cmd.Run()
	// ProcessState is nil when the program never started; its ExitCode method then returns -1.
	res := Result{Stdout: out.String(), Stderr: errb.String(), ExitCode: cmd.ProcessState.ExitCode()}

	var exitErr *exec.ExitError
	switch {
	case err == nil:
		return res, nil
	case errors.Is(ctx.Err(), context.DeadlineExceeded):
		return res, fmt.Errorf("%s: %w after %s", name, ErrTimeout, timeout)
	case errors.As(err, &exitErr):
		// Non-zero exit is data for the caller, like `cmd || handle`; keep the error for errors.As.
		return res, fmt.Errorf("%s: exit status %d: %w", name, res.ExitCode, err)
	default:
		return res, fmt.Errorf("%s: %w", name, err) // not found, permission denied...
	}
}
go
package runcmd

import (
	"context"
	"errors"
	"os/exec"
	"strings"
	"testing"
	"time"
)

func TestSuccessCapturesStdout(t *testing.T) {
	res, err := Run(context.Background(), 5*time.Second, "printf", "%s\n", "hello")
	if err != nil || res.Stdout != "hello\n" || res.ExitCode != 0 {
		t.Fatalf("res=%+v err=%v", res, err)
	}
}

func TestArgumentsAreNotParsedByAShell(t *testing.T) {
	// In a shell this would run `echo pwned`; as an argv element it is just text.
	evil := "x; echo pwned $(id -u) *"
	res, err := Run(context.Background(), 5*time.Second, "printf", "%s", evil)
	if err != nil || res.Stdout != evil {
		t.Fatalf("stdout=%q err=%v, want the argument echoed verbatim", res.Stdout, err)
	}
}

func TestNonZeroExitIsReportedWithItsCode(t *testing.T) {
	res, err := Run(context.Background(), 5*time.Second, "sh", "-c", "echo oops >&2; exit 7")
	var ee *exec.ExitError
	if !errors.As(err, &ee) || res.ExitCode != 7 || !strings.Contains(res.Stderr, "oops") {
		t.Fatalf("res=%+v err=%v", res, err)
	}
}

func TestMissingProgram(t *testing.T) {
	res, err := Run(context.Background(), time.Second, "definitely-not-a-program-xyz")
	if !errors.Is(err, exec.ErrNotFound) || res.ExitCode != -1 {
		t.Fatalf("res=%+v err=%v", res, err)
	}
}

func TestTimeoutKillsTheChild(t *testing.T) {
	start := time.Now()
	_, err := Run(context.Background(), 200*time.Millisecond, "sleep", "30")
	if !errors.Is(err, ErrTimeout) {
		t.Fatalf("err=%v, want ErrTimeout", err)
	}
	if d := time.Since(start); d > 5*time.Second {
		t.Fatalf("took %s, the child was not killed", d)
	}
}
text
module academy/shell-scripting-text-processing

go 1.24

And the shell side: a start script that loads configuration, validates, and execs the Go binary so the binary, not the shell, receives SIGTERM.

bash
#!/bin/sh
# Start script for a Go binary: load config, validate, then `exec` so the binary replaces
# the shell and becomes PID 1 / the supervised process. Without exec, SIGTERM goes to the
# shell, which neither forwards it nor exits, and the Go program never drains.
# POSIX sh: works in a distroless-adjacent alpine image with only /bin/sh.
set -eu

BIN=${ORDERS_BIN:-/usr/local/bin/orders-api}
: "${PORT:=8080}"
: "${LOG_LEVEL:=info}"
export PORT LOG_LEVEL

if [ -n "${ORDERS_ENV_FILE:-}" ] && [ -r "$ORDERS_ENV_FILE" ]; then
  set -a; . "$ORDERS_ENV_FILE"; set +a     # trusted file, mode 0600, written by the platform
fi
[ -x "$BIN" ] || { echo "start: $BIN is not executable" >&2; exit 126; }

# Run migrations or other one-shot steps here, never in the background:
#   "$BIN" migrate up || exit $?

exec "$BIN" "$@"

The Go angle ​

  • No shell in the middle. exec.Command("printf", "%s", userInput) passes an argument vector to execve; there is no word splitting, no globbing and no $(...). The runcmd test passes x; echo pwned $(id -u) * and gets the literal text back. Use exec.Command("sh", "-c", ...) only when you want the shell, and then quote with care.
  • Deadlines are a first-class value. exec.CommandContext kills the child when the context ends; Cmd.WaitDelay (added in Go 1.20, see the saved release notes) bounds the wait for output pipes held open by grandchildren. Shell scripts need timeout (not on stock macOS) for the same.
  • Exit status is data. errors.As(err, &exitErr) gives ExitCode(); a signal-killed child reports -1 on Unix. That mirrors $? and 128+N.
  • Scanning big text. bufio.Scanner has a default maximum token size of 64 KiB (MaxScanTokenSize = 64 * 1024); a log line longer than that stops the scan with bufio.ErrTooLong unless you call Buffer, which logsummary does. awk has no such limit.
  • Same numbers, tested. The Go test reads the same data/access.txt and asserts 12 requests, 9/1/2 per class, /orders average 0.487 and 16.7 % errors, which are the awk outputs, so a refactor cannot drift.
  • Exit codes as an interface. The logsummary command exits 3 when the 5xx ratio exceeds -max-error, so a cron job or CI step can fail on it; the shell integration is logsummary -max-error 0.05 < access.txt || notify.
  • Replacing one pipeline stage. Because logsummary reads stdin and writes stdout, it drops into tail -n 100000 access.txt | logsummary. Replace stages one at a time.
  • Flags and environment for such commands (subcommands, flag, os.LookupEnv, log/slog) are in CLI Flags, Subcommands, Environment Variables & Logging; the signal handling a long-running Go service needs is in OS Processes, Signals & Graceful Shutdown.
  • Go binary wrappers. The go-wrapper.sh pattern (set defaults with : "${PORT:=8080}", optional env file with set -a, validate the binary, then exec "$BIN" "$@") is the standard entrypoint for Go images that still need a shell, e.g. FROM alpine; a distroless or scratch image has no shell, so the binary must read its own configuration.

Laravel ​

Before ​

A deploy snippet found in many wikis:

bash
cd /var/www/orders
git pull
composer install
php artisan migrate
php artisan config:cache
php artisan queue:restart

It runs in place on live code, has no set -e (a failed composer install still runs migrate), asks for confirmation in production (migrate refuses to run non-interactively without --force), caches config from whatever .env is present and keeps no previous release to return to.

After ​

bash
#!/usr/bin/env bash
# Laravel release steps as a script: the order matters and every step must be able to fail the deploy.
# Run from the NEW release directory, before traffic moves to it (see scripts/deploy.sh).
set -euo pipefail

cd "${1:?usage: artisan-release.sh RELEASE_DIR}"
artisan() { php artisan "$@" --no-interaction; }     # never prompt in a script

[ -f .env ] || { echo "no .env in $PWD (symlink shared/.env first)" >&2; exit 4; }

composer install --no-dev --prefer-dist --optimize-autoloader --no-interaction

# --force: in production, migrate refuses to run without it (it asks for confirmation).
# --isolated: take an atomic lock via the cache so two servers do not migrate at once.
# Careful: a server that loses the race skips the migration AND exits 0 (Laravel 13 docs),
# so "exit 0" does not prove this host ran the migration.
artisan migrate --force --isolated

# Rebuild every cache from THIS release's config and routes (config:cache, route:cache,
# view:cache and event:cache in one command).
artisan optimize

# Queue workers hold the old code in memory: signal them to exit after the current job;
# the process manager (systemd, Supervisor) starts new ones.
artisan queue:restart

# Exit-code contract used by scripts: 0 success, non-zero failure.
# `php artisan down` / `up` bracket risky migrations; --retry sets the Retry-After header.
#   artisan down --retry=60 --secret="$BYPASS_TOKEN"   # before
#   artisan up                                         # after

A scheduled task needs exactly one cron line (see the crontab above) because the Laravel scheduler decides which tasks are due; the docs say to add "a single cron configuration entry to our server that runs the schedule:run command every minute".

The Laravel angle ​

  • Exit codes are the contract. A command exits 0 when handle() returns nothing; return an integer for another status, or call fail(), which "will immediately terminate execution of the command and return an exit code of 1" (Artisan docs). Scripts branch on $?.
  • Never prompt in scripts. --no-interaction (-n) disables questions; migrate --force is required in production; optimize builds the config, event, route and view caches in one command (Laravel deployment docs) and optimize:clear removes them.
  • --isolated locks via the cache. Commands that implement Illuminate\Contracts\Console\Isolatable (and migrate --isolated) take, when invoked with --isolated, an atomic lock through the application's default cache driver; "the command will still exit with a successful exit status code" when it did not run, so a script cannot tell "ran" from "skipped" from $? alone.
  • Queue workers hold old code in memory. php artisan queue:restart tells workers to exit after their current job; the process manager (systemd, Supervisor) starts new ones with the new release.
  • Shelling out from PHP. The Process facade runs a command with a working directory, a timeout (60 s by default; Process::timeout(120); forever() disables it), ->throw() to turn failure into an exception and exitCode(), output(), errorOutput() to inspect it.
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Isolatable;
use Illuminate\Support\Facades\Process;

// php artisan exports:compress --isolated            (one instance at a time: the lock is taken ONLY when --isolated is passed)
// php artisan exports:compress --isolated --dry-run  (print the command, do nothing)
class CompressExports extends Command implements Isolatable
{
    protected $signature = 'exports:compress {--dry-run : Print the command, do nothing}';
    protected $description = 'Compress CSV exports older than 7 days';

    public function handle(): int
    {
        $dir = escapeshellarg(storage_path('app/exports'));
        // find -print0 | xargs -0 is the NUL-safe pipeline from this chapter; the shell runs it, PHP only builds it.
        $cmd = "find {$dir} -type f -name '*.csv' -mtime +7 -print0 | xargs -0 -r gzip -9";

        if ($this->option('dry-run')) {
            $this->line("DRY-RUN: {$cmd}");
            return self::SUCCESS;
        }

        $result = Process::timeout(300)->run($cmd);
        if ($result->failed()) {
            $this->error($result->errorOutput());
            return $result->exitCode() ?: self::FAILURE;
        }
        return self::SUCCESS;
    }
}

php -l reports "No syntax errors" for this file (PHP 8.5.0 on the build host); it was not executed inside a Laravel application. Note the invocation: Isolatable only makes the --isolated option available; Laravel takes the lock "when the command is invoked with that option", so the cron line or script must pass --isolated.

Solving the classic problems ​

ProblemNaive approachSafe approachSection
Script keeps going after an errorNothingset -euo pipefail, explicit || handle for expected failuresExit status
Spaces in filenamesfor f in $(ls)for f in ./* or find -print0 | xargs -0find and xargs
Half-written outputWrite in placeTemp file in the same directory, then mvtrap
Two cron runs overlapPID fileflock -n or mkdir lockLocks
Re-running duplicates workecho >> fileCheck, then act; ln -sfn, mkdir -p, version markerIdempotence
Secret in logs or psArgument or set -xstdin, 0600 file, secret managerEnv and secrets
Works on Mac, not on CIGNU-only flagsCommon subset, or run CI in a containerPortability
Deploy has no way backOverwrite in placeRelease directories and an atomic symlink switchbelow

Writing a deploy script ​

The goal: copy a build to a host, migrate, switch traffic atomically, check health, roll back on failure, keep a few old releases. The script is idempotent (the same version twice is a no-op), supports --dry-run, validates the version because it becomes a path, and uses one helper for the one portability difference (mv -T on GNU, mv -h on BSD).

bash
#!/usr/bin/env bash
# deploy.sh: ship a Go binary and a Laravel release to one host, safely.
# Idempotent (re-running with the same version changes nothing), supports --dry-run,
# keeps the previous release for rollback, checks health before and after the switch.
# Every external command goes through run() so --dry-run prints instead of acting.
# Layout under $ROOT:  releases/<version>/  current -> releases/<version>  shared/
set -euo pipefail

ROOT=${DEPLOY_ROOT:-/srv/orders}
HEALTH_URL=${HEALTH_URL:-http://127.0.0.1:8080/healthz}
KEEP=${KEEP:-3}
DRY_RUN=0

usage() { echo "usage: ${0##*/} [--dry-run] VERSION ARTIFACT_DIR" >&2; exit 2; }
log()   { printf '%s deploy: %s\n' "$(date -u +%H:%M:%S)" "$*" >&2; }
run()   { if [ "$DRY_RUN" = 1 ]; then { printf 'DRY-RUN:'; printf ' %q' "$@"; printf '\n'; } >&2; else "$@"; fi; }

while [ "$#" -gt 0 ]; do
  case $1 in
    --dry-run) DRY_RUN=1; shift ;;
    -h|--help) usage ;;
    --) shift; break ;;
    -*) echo "unknown option: $1" >&2; usage ;;
    *) break ;;
  esac
done
[ "$#" -eq 2 ] || usage
VERSION=$1
ARTIFACTS=$2
case $VERSION in *[!A-Za-z0-9._-]*|'') echo "bad version: $VERSION" >&2; exit 2 ;; esac  # no / or spaces: it becomes a path

REL="$ROOT/releases/$VERSION"

# Replace the symlink $2 with $1 atomically. GNU mv needs -T (treat target as a file);
# BSD/macOS mv needs -h (do not follow a symlink to a directory).
swap_link() {
  case $(uname -s) in
    Darwin|*BSD) mv -fh "$1" "$2" ;;
    *)           mv -T "$1" "$2" ;;      # GNU coreutils and BusyBox
  esac
}

healthy() { curl --fail --silent --show-error --max-time 5 --retry 5 --retry-delay 1 --retry-connrefused "$HEALTH_URL" >/dev/null; }

# 1. Idempotency: already live? Then there is nothing to do.
if [ -L "$ROOT/current" ] && [ "$(readlink "$ROOT/current")" = "$REL" ]; then
  log "$VERSION is already current; nothing to do"
  exit 0
fi

# 2. Unpack into a new release directory (never into the live one).
[ -x "$ARTIFACTS/orders-api" ] || { echo "missing $ARTIFACTS/orders-api" >&2; exit 4; }
run mkdir -p "$REL" "$ROOT/shared"
run cp -p "$ARTIFACTS/orders-api" "$REL/orders-api"
if [ -d "$ARTIFACTS/laravel" ]; then run cp -R "$ARTIFACTS/laravel/." "$REL/"; fi
run ln -sfn "$ROOT/shared/.env" "$REL/.env"

# 3. Laravel steps, against the NEW release, before traffic moves. Decide from the ARTIFACT:
#    in a dry run $REL was never created, so testing it would silently skip these steps.
HAS_ARTISAN=0
if [ -f "$ARTIFACTS/laravel/artisan" ]; then HAS_ARTISAN=1; fi
if [ "$HAS_ARTISAN" = 1 ]; then
  run php "$REL/artisan" migrate --force --no-interaction
  run php "$REL/artisan" optimize
fi

# 4. Atomic switch: build a temp symlink, then rename(2) it over the old one.
PREV=""
if [ -L "$ROOT/current" ]; then PREV=$(readlink "$ROOT/current"); fi
run ln -sfn "$REL" "$ROOT/current.new"
if [ "$DRY_RUN" = 1 ]; then log "DRY-RUN: swap current -> $REL"; else swap_link "$ROOT/current.new" "$ROOT/current"; fi

# 5. Restart and verify; roll back on failure. `if ! cmd` is exempt from set -e, so a failed
#    restart reaches the rollback instead of leaving `current` on a release that never started.
rollback() {
  if [ -n "$PREV" ]; then
    ln -sfn "$PREV" "$ROOT/current.new"
    swap_link "$ROOT/current.new" "$ROOT/current"
    systemctl restart orders-api || true
  else
    rm -f "$ROOT/current"        # first deploy: nothing to go back to; a retry must not look "already current"
  fi
}
if [ "$DRY_RUN" = 1 ]; then
  run systemctl restart orders-api
else
  if ! systemctl restart orders-api; then
    log "restart failed; rolling back to ${PREV:-none}"; rollback; exit 6
  fi
  if ! healthy; then
    log "health check failed; rolling back to ${PREV:-none}"; rollback; exit 5
  fi
fi
if [ "$HAS_ARTISAN" = 1 ]; then run php "$ROOT/current/artisan" queue:restart; fi

# 6. Keep the newest $KEEP releases (names sort by mtime with ls -t; versions here contain no spaces).
if [ "$DRY_RUN" = 0 ]; then
  # shellcheck disable=SC2012  # release names are validated above: no spaces or newlines
  ls -1t "$ROOT/releases" | tail -n +"$((KEEP + 1))" | while read -r old; do
    [ "$ROOT/releases/$old" = "$REL" ] || rm -rf "${ROOT:?}/releases/$old"
  done
fi
log "deployed $VERSION (previous: ${PREV:-none})"
1  $ deploy.sh 1.4.2 art/           releases/1.4.2 created; migrate; optimize; current.new -> mv -> current
2  $ systemctl restart orders-api   new Go binary starts from releases/1.4.2/orders-api
3  $ curl --retry 5 .../healthz     fails (exit 22)
4  deploy: health check failed; rolling back to /srv/orders/releases/1.4.1
5  $ ln -sfn releases/1.4.1 current.new ; mv -T current.new current ; systemctl restart ; exit 5

Real dry-run output (scratch paths abbreviated) and the offline test run:

text
DRY-RUN: mkdir -p <scratch>/droot/releases/1.4.2 <scratch>/droot/shared
DRY-RUN: cp -p <scratch>/art/orders-api <scratch>/droot/releases/1.4.2/orders-api
DRY-RUN: ln -sfn <scratch>/droot/shared/.env <scratch>/droot/releases/1.4.2/.env
DRY-RUN: ln -sfn <scratch>/droot/releases/1.4.2 <scratch>/droot/current.new
09:36:37 deploy: DRY-RUN: swap current -> <scratch>/droot/releases/1.4.2
DRY-RUN: systemctl restart orders-api
09:36:37 deploy: deployed 1.4.2 (previous: none)

The eleven checks of tests/deploy-test.sh (first deploy, no-op rerun, version switch, health-check rollback with exit 5, failed-restart rollback with exit 6 and a clean retry, dry run of a new Laravel release still listing migrate and optimize, bad version rejected with exit 2, dry run changes nothing) all print ok. A failed systemctl restart must reach the rollback: under set -e a bare failing command would exit first and leave current on a release that never started, so the script tests it with if ! systemctl restart. Where this script sits: in CI it is called from a GitHub Actions or GitLab CI job over SSH; with Kubernetes the same job is a rollout (kubectl rollout status, a Helm release, or an Argo CD sync) rather than a symlink; with Terraform or Ansible the host preparation is declarative (Configuration Management with Ansible) and the script shrinks to "ship the artefact".

Log analysis one-liners ​

The sample is data/access.txt (12 lines of an Nginx-style access log with request time as the last field). Real output from the lab:

bash
#!/usr/bin/env bash
# Log analysis one-liners on data/access.txt. POSIX/BSD-safe: runs on macOS and Linux.
# Format: ip - - [time] "METHOD path HTTP/x" status bytes seconds
# No pipefail here on purpose: `sort | head -3` makes sort die with SIGPIPE (status 141) as soon
# as head has its three lines, and under pipefail that would fail the whole script. Use
# pipefail for pipelines whose every stage must succeed; here, grep's "no match" (1) is also data.
set -eu
cd "$(dirname "$0")/../data"

echo "--- requests per status class (awk: fields, array, END)"
awk '{ c = substr($9, 1, 1) "xx"; n[c]++ } END { for (k in n) print k, n[k] }' access.txt | sort

echo "--- top client IPs (cut | sort | uniq -c | sort -rn | head)"
cut -d' ' -f1 access.txt | sort | uniq -c | sort -rn | head -3

echo "--- 5xx lines only (grep -E: ERE alternation, anchors on a field)"
grep -E '" 5[0-9]{2} ' access.txt || true   # no match is exit 1: not a failure of the script

echo "--- slowest 3 requests (sort on the last field, numeric, reverse)"
awk '{ print $NF, $6, $7 }' access.txt | sort -rn | head -3 | tr -d '"'

echo "--- average and maximum latency per path, query string stripped (awk)"
awk '{ split($7, p, "?"); s[p[1]] += $NF; n[p[1]]++; if ($NF > m[p[1]]) m[p[1]] = $NF }
     END { for (k in s) printf "%-16s n=%d avg=%.3f max=%.3f\n", k, n[k], s[k]/n[k], m[k] }' access.txt | sort

echo "--- error ratio (awk, one pass)"
awk '$9 >= 500 { e++ } END { printf "%d of %d = %.1f%%\n", e, NR, 100 * e / NR }' access.txt

echo "--- requests per minute (sed capture group, ERE with -E on both GNU and BSD)"
sed -E 's/^[^[]*\[[^:]*:([0-9]{2}:[0-9]{2}):.*/\1/' access.txt | sort | uniq -c

echo "--- decode one escape (%20) with sed; real decoding needs a proper tool"
echo 'blue%20shirt' | sed 's/%20/ /g'

echo "--- BRE vs ERE: the same match, two syntaxes"
grep    'orders/[0-9][0-9]*'  access.txt | wc -l | tr -d ' '     # BRE: * repeats, \+ is a GNU extension
grep -E 'orders/[0-9]+'       access.txt | wc -l | tr -d ' '     # ERE: + ? | () {} are operators

echo "--- tee: save an intermediate result and keep going"
grep -E '" 5[0-9]{2} ' access.txt | tee /dev/stderr | wc -l | tr -d ' '

echo "--- xargs: one command per input, safe with NUL separators"
printf 'a b\0c\0' | xargs -0 -n1 printf '[%s]\n'
text
--- requests per status class (awk: fields, array, END)
2xx 9
4xx 1
5xx 2
--- top client IPs (cut | sort | uniq -c | sort -rn | head)
   5 203.0.113.7
   3 198.51.100.4
   2 198.51.100.9
--- slowest 3 requests (sort on the last field, numeric, reverse)
1.002 POST /orders
0.340 POST /orders
0.120 POST /orders
--- error ratio (awk, one pass)
2 of 12 = 16.7%
--- requests per minute (sed capture group, ERE with -E on both GNU and BSD)
   6 10:00
   4 10:01
   2 10:02
--- BRE vs ERE: the same match, two syntaxes
5
5

On a real server, add the filters in this order: select the time window first (grep '29/Nov/2026:10:' or awk '$4 >= "[29/Nov/2026:10:00"'), then reduce with awk, then sort. Prefer LC_ALL=C for grep and sort on large ASCII logs. When the logs are JSON (structured logging, which CLI Flags, Subcommands, Environment Variables & Logging recommends for Go services), use jq -r 'select(.level=="ERROR") | .msg' rather than grep. For docker logs or kubectl logs the stream is the same: pipe it, and remember that docker logs writes the container's stderr to your stderr, so add 2>&1 before the pipe.

Other recurring jobs ​

JobPatternWarning
Rotate and compress logsfind /var/log/app -name '*.log' -mtime +1 -print0 | xargs -0 gzip; real systems use logrotategzip and a process still writing the file: rotate with copytruncate or signal the app
Back up a databasepg_dump db | gzip > "$TMP/db.sql.gz" then mv; with pipefailCheck the size, test the restore
Wait for a serviceuntil curl -fsS http://db:8080/healthz; do sleep 1; done with a deadline counterAn unbounded loop hangs CI forever
Run in parallelxargs -P4 -n1 cmd < listOutput interleaves; use -I{} and write one file per job
Update an image tag in manifestsyq -i '.spec.template.spec.containers[0].image = "x:1.4.3"' deploy.yamlA Helm values file or Kustomize images: is cleaner; Argo CD then syncs the Git change
Bulk renamefor f in ./*.JPG; do mv -- "$f" "${f%.JPG}.jpg"; done-- and quoting; dry run with echo mv first
Check a certificateecho | openssl s_client -connect host:443 2>/dev/null | openssl x509 -noout -enddateThe 2>/dev/null hides real errors; log them in production
Terraform in CIterraform fmt -check -recursive && terraform validateExit codes drive the pipeline step
Nginx config check before reloadnginx -t && nginx -s reload&& is the correct guard; never reload on a broken config
Container entrypointexec "$@" as the last lineWithout exec the shell is PID 1 and eats SIGTERM

Choosing ​

Which shell ​

SituationChooseWhy
Script runs in Alpine/BusyBox, RUN steps, Makefile recipes, sh -cPOSIX sh, test with dashNo bash guaranteed
Ops scripts on Linux servers you controlbash 4+, #!/usr/bin/env bash, set -euo pipefailArrays, [[ ]], pipefail
Must run on stock macOS toobash 3.2 subset or POSIXNo associative arrays, mapfile, ${x,,}
Interactive daily usezsh or bashYour choice; do not deploy zsh scripts
Distroless / scratch imageNo shell: the binary does its own start-upSmaller attack surface

Which tool for the text job ​

JobToolSwitch when
Is this string in these lines?grep -F / grep -EYou need captures: sed/awk
Replace text in linessed -E 's///'Structured file: jq/yq
Columns, sums, group-byawkQuoted CSV or more than ~20 lines of awk: Go/Python
Count distinctsort | uniq -c | sort -rnMore than memory: sort spills to disk; or a database
JSON in, JSON outjqA jq program past ~10 lines: Go
YAML edityq (v4)Helm/Kustomize can do it declaratively
Many filesfind -print0 | xargs -0Needs state across files: Go

Which lock ​

SituationLock
One Linux host, cron overlapflock -n
Must run on macOS and Linuxmkdir lock with an EXIT trap
Several hostsDatabase advisory lock, Redis lock, or a leader-elected controller (Kubernetes Lease)
Kubernetes batchCronJob with concurrencyPolicy: Forbid
Laravel commandIsolatable plus calling it with --isolated (cache lock)

Which tests and checks ​

Script size and riskMinimum
10-line glueshellcheck and bash -n
Deploy or data-changing scriptshellcheck, shfmt, a dry-run flag, a Bats or plain-bash test with stubs on PATH
Anything with money, deletes or production credentialsAll of the above, code review, run first with --dry-run in production, and prefer a typed language

In architecture: from a single process to a distributed system ​

Monolith: one host, a few scripts ​

A single VM runs Nginx, PHP-FPM or a Go binary, and a database. The scripts are deploy.sh, a backup job and a log rotation, started by hand and by cron. The rules that matter: strict mode, quoting, a lock on every cron job, temp files in mktemp, atomic publish with mv, logs on stderr. The code is in one Git repository next to the application, linted in CI.

Modular monolith: scripts as a shared toolbox ​

Several modules and environments (staging, production) share the same deploy script, parameterised by environment variables and flags, not copied. The script is the contract: deploy.sh [--dry-run] VERSION ARTIFACT_DIR, documented exit statuses, one configuration file per environment loaded by the safe .env loader, a Bats suite in the repository. When two scripts need the same function, extract a sourced library only if it is tested; otherwise that is the signal to write a Go CLI.

Microservices: scripts at the edges, not in the middle ​

With dozens of services the scripts live in CI and in container images: docker build and push steps in GitHub Actions or GitLab CI; Dockerfile RUN lines; entrypoint scripts that exec the service; Helm hooks; kubectl one-liners. Rules: keep each CI shell step short and call a versioned script from the repository instead of pasting 80 lines into YAML; make every script safe to retry because CI retries; never put business logic in an entrypoint; use exec; use the image's own tools (a distroless image has no shell, so debugging uses an ephemeral debug container). Terraform and Ansible own infrastructure state; a shell script that "ensures" infrastructure drifts from the code and should become a Terraform resource or an Ansible task. Argo CD or Flux own "what is deployed"; a deploy script that runs kubectl apply by hand competes with them.

Distributed data and fleets: where a script stops being enough ​

Across many hosts a script faces the problems of distributed systems: partial failure (3 of 10 hosts updated), ordering, concurrency control across machines, secrets distribution, and observability. ssh host script in a loop has no rollback and no inventory; xargs -P over hosts has no backpressure. The answers are the tools in the neighbouring chapters: Ansible for idempotent host state and rolling changes, Kubernetes rollouts with readiness probes for services, queues and leader election for singleton jobs, and a lock in a shared store instead of a file. Logs from a fleet go to a central system; a script's logger -t deploy (syslog) or JSON on stdout (collected by containerd, Docker or the node agent) is how its output joins them. Time and locale vary across hosts: pin LC_ALL=C and TZ=UTC in scripts that sort or parse dates.

Scaling path: 1x, 10x, 100x ​

ScaleWhat the shell is used forWhat goes wrongStep up
1 host, 1 operatorAd-hoc commands, cron jobs, a deploy scriptTypos, spaces in names, missing cleanupStrict mode, quoting, shellcheck
10 hosts, a teamShared scripts, CI steps, runbooksDrift between hosts, no tests, copy-pasteVersion control, Bats, Ansible for host state
100 hosts or many servicesCI glue, container entrypoints, Helm hooksEvery script is critical and nobody owns it; scripts reimplement a platformMove logic into Go tools and Terraform/Ansible/Argo CD; keep shell for thin wrappers; policy checks in CI

Lab ​

Labelling: every command below was run on the build host (macOS, /bin/bash 3.2.57, BSD userland, jq-1.7.1-apple, zsh 5.9, Go 1.27.4) from the snippet directory docs/snippets/platform/shell-scripting-text-processing/, and the outputs are copied from pipeline/sources/shell-scripting-text-processing/lab-host-output.txt, except where a step says "expected, not run" (Linux-only tools: flock, GNU sed, gawk; and shellcheck, shfmt, bats and yq, which are not installed here). Nothing needs Docker, root or network access.

1. Strict mode, one experiment at a time (ran) ​

bash
bash scripts/strict-mode.sh

Expected output is the block shown in Exit status: false; echo still running prints "still running", set -e stops, set -u reports unbound variable, false | true reports 0 and with pipefail reports 1, PIPESTATUS prints 1 0 1, local x=$(false) does not stop, yes | head -1 gives 141.

2. Quoting and splitting (ran) ​

bash
bash scripts/pitfalls.sh

Compare the 2 args lines with the 1 args lines (block in Quoting); the last two lines show an array expanded with and without quotes: 2 args: [my report.txt] [a.txt] against 3 args: [my] [report.txt] [a.txt].

3. Five shells, one program (ran) ​

bash
sh scripts/shells-compared.sh
text
=== bash (/bin/bash)
    unquoted word split gives 2 word(s)
    array literal ok, first=xy
    BASH_VERSION=3.2.57(1)-release ZSH_VERSION=unset
=== sh (/bin/sh)
    BASH_VERSION=3.2.57(1)-release ZSH_VERSION=unset      (macOS sh is bash 3.2 in POSIX mode)
    echo -e:    -   e       a  	                        (prints "-e"; bash prints a tab)
=== dash (/bin/dash)
    unquoted word split gives 2 word(s)
    dash: 4: Syntax error: "(" unexpected                 (arrays do not exist)
=== zsh (/bin/zsh)
    unquoted word split gives 1 word(s)                   (no splitting by default)
    array literal ok, first=x                             (1-based)
=== ksh (/bin/ksh)
    local-in-function: ksh: line 7: local: not found

4. Text processing on a log (ran) ​

bash
bash scripts/text-pipeline.sh && bash scripts/json-yaml.sh

Outputs are the blocks in Log analysis one-liners and jq.

5. The safe template: success, dry run, usage error, lock held, SIGTERM (ran) ​

The five commands and their real transcripts are in trap: exits 0, 0, 4, 3 and 143, and no safe-template.* directory remains.

6. The deploy script, offline (ran) ​

bash
bash tests/deploy-test.sh              # eleven "ok" lines, exit 0
bash tests/safe-template-test.sh       # eight "ok" lines, exit 0
mkdir -p /tmp/art && printf '#!/bin/sh\n' > /tmp/art/orders-api && chmod +x /tmp/art/orders-api   # the artefact the dry run checks for
DEPLOY_ROOT=/tmp/droot bash scripts/deploy.sh --dry-run 1.4.2 /tmp/art   # prints DRY-RUN lines only; /tmp/droot is not created

7. curl against a local server (ran) ​

bash
bash scripts/curl-api.sh

Shows exit 0 for a 404 without --fail, exit 22 with it, --retry turning two 503 responses into a final 200 and exit 7 for a refused connection (block in curl).

8. Go: the awk job as a tested program (ran) ​

bash
cd go && gofmt -l . && go vet ./... && go test -race -count=1 ./...
go build -o /tmp/logsummary ./cmd/logsummary && /tmp/logsummary -max-error 0.1 < ../data/access.txt; echo "exit $?"
text
gofmt -l: []
go vet: ok
ok  	academy/shell-scripting-text-processing/cmd/logsummary	1.366s
ok  	academy/shell-scripting-text-processing/logsummary	1.365s
ok  	academy/shell-scripting-text-processing/runcmd	1.552s
2xx 9
4xx 1
5xx 2
/healthz         n=2 avg=0.001 max=0.001
/orders          n=3 avg=0.487 max=1.002
/orders/1001     n=2 avg=0.016 max=0.020
/orders/1002     n=2 avg=0.013 max=0.015
/orders/9999     n=1 avg=0.008 max=0.008
/products        n=2 avg=0.049 max=0.050
2 of 12 = 16.7%
exit 3

(go run would print exit status 3 and return 1; the compiled binary returns 3.)

9. Linux-only and tool-dependent steps (expected, not run) ​

bash
flock -n /var/lock/job.lock sleep 5 & sleep 1; flock -n /var/lock/job.lock echo second; echo "rc=$?"   # rc=1: busy
shellcheck scripts/*.sh                      # expected: clean, or SC2012 only where a disable comment explains it
shfmt -d -i 2 -ci scripts/*.sh               # expected: a diff for any script not yet formatted that way
bats tests/safe-template.bats                # expected: 5 tests, "ok 1 ... ok 5"
yq '.service.replicas' data/config.yaml      # 3
sed -i 's/hello/bye/' file                   # GNU: works; BSD: error shown in the portability block

10. Kubernetes, Docker and CI in context (expected, not run) ​

bash
docker run --rm -v "$PWD":/w -w /w koalaman/shellcheck-alpine shellcheck scripts/*.sh   # lint without installing anything
kubectl logs deploy/orders-api --since=10m 2>&1 | jq -r 'select(.level=="ERROR") | .msg' | sort | uniq -c | sort -rn

Common misconceptions ​

BeliefReality
set -e makes scripts safeIt is disabled in if/&&/|| contexts, in pipelines without pipefail and in functions called from them; handle errors explicitly
Quote only when there are spacesQuote every expansion; unset, empty, * and leading - also break unquoted use
#!/bin/sh is bashIt is dash, ash, or bash in POSIX mode depending on the system
sed -i is portableGNU -i[SUFFIX] versus BSD -i SUFFIX; use -i.bak and delete the backup
grep returns an error when nothing matchesIt returns 1 (no match) and 2 (error); under set -e the 1 aborts the script unless guarded
uniq removes duplicatesIt collapses only adjacent duplicates; sort first
ls | xargs is fineParsing ls breaks on spaces and newlines; use find -print0 | xargs -0 or a glob
trap ... EXIT always runsNot on kill -9; handle INT/TERM by calling exit so EXIT fires
A PID file is a lockIt is racy and goes stale; use flock or mkdir
source .env is safeIt executes the file; parse KEY=VALUE lines without eval
curl fails on HTTP errorsOnly with --fail; add timeouts and retries
Environment variables keep secrets privateSame-user processes read them; arguments are visible to everyone; use stdin or a 0600 file
zsh scripts run anywhere bash doeszsh differs (no word splitting, 1-based arrays); write bash or POSIX for deployment
Shell is faster than Go for textStreaming awk is fast to write; a compiled program wins on big data, tests and structure

Cheat sheet ​

TopicWhat to remember
Header#!/usr/bin/env bash, set -euo pipefail, IFS=$'\n\t' optional
Quoting"$var", "$@", "${arr[@]}", "$(cmd)"; '...' for literal
Defaults${v:-d} use, ${v:=d} assign, ${v:?msg} require, ${v%.*} strip suffix
Tests[ ] POSIX with quoted operands; [[ ]] bash; (( )) for numbers; case for patterns
Streams> >> < 2>&1 (order matters) | tee; logs to stderr
Filesfind ... -print0 | xargs -0; globs with a no-match guard; never parse ls
grep-E ERE, -F fixed, -q quiet, exit 0/1/2
sedsed -E 's/a/b/g', in place sed -i.bak ... && rm f.bak
awkawk -F, '{s+=$3} END{print s}', n[$1]++ group-by, -v to pass values
Countingsort | uniq -c | sort -rn | head
jq / yqjq -r, select, //, -e, --arg; yq '.a.b', yq -i
curl--fail --silent --show-error --location --max-time N --retry N
Cleanuptmp=$(mktemp -d ...); trap cleanup EXIT; mv to publish
Locksflock -n 9 (Linux); mkdir lockdir (portable); not a PID file
Safety--dry-run through one run(); idempotent steps; verify, then switch; keep the previous release
CronSet PATH, absolute paths, escape \%, wrapper with lock and log
PortabilityNo sed -i '' vs -i assumptions, no grep -P, no bash 4 features on macOS
Qualityshellcheck (SC2086 SC2046 SC2155 SC2164), shfmt, Bats, bash -n
Leave shellMore than ~100 lines, data structures, retries, tests, Windows: Go or Python

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A script runs rm -rf $BUILD_DIR/cache and one day deletes far more than intended. What happened and what three habits prevent it? Must-know ​

Answer

Answer: BUILD_DIR was unset or empty, so the unquoted expansion became rm -rf /cache, or, when the variable held a space, two separate paths. Prevent it with set -u (unset variable is an error), quoting ("$BUILD_DIR") and a guard such as : "${BUILD_DIR:?BUILD_DIR is required}" before any destructive command. shellcheck reports the unquoted use as SC2086. See Quoting and Variables.

2 — Why does set -e not stop the script after grep -q ERROR log || true; false | true, and what does pipefail change? Must-know ​

Answer

Answer: set -e ignores failures on the left of || and && and in all but the last stage of a pipeline, so the first command is deliberately guarded and false | true has status 0 (the last stage). With set -o pipefail the pipeline's status is that of the last non-zero stage (1), and set -e then fires. The Bash manual lists every context where -e is suppressed. See Exit status.

3 — What is the difference between cmd > out 2>&1 and cmd 2>&1 > out? Must-know ​

Answer

Answer: Redirections are applied left to right. In the first, fd 1 is pointed at out and then fd 2 is made a copy of fd 1, so both streams go to the file. In the second, fd 2 is first copied from fd 1 (still the terminal) and only then is fd 1 redirected, so stderr stays on the terminal. See Pipes and redirection and the diagram.

4 — Why is ls | xargs rm wrong, and what is the safe form? Must-know ​

Answer

Answer: ls output is for humans: names containing spaces or newlines are split apart by xargs, so you delete the wrong files. The safe form uses a NUL separator that cannot occur in a name: find DIR -type f -name '*.tmp' -print0 | xargs -0 rm --, or find ... -exec rm -- {} +, or a glob loop. See find and xargs.

5 — How do you make a cron job that must never run twice at the same time? Compare flock and mkdir. Must-know ​

Answer

Answer: Take an atomic lock at the start and exit (usually with status 0 and a log line) when it is held. flock -n 9 on a descriptor opened with exec 9>file is held by the kernel and released even after kill -9, but it is Linux (util-linux) only. mkdir lockdir is atomic everywhere but leaves a stale directory after kill -9, so release it in an EXIT trap. A PID file check is racy. See Locks.

6 — A script uses sed -i 's/a/b/' file and works on Ubuntu CI but fails on a developer's Mac. Why, and what is the portable fix? Important ​

Answer

Answer: GNU sed takes the backup suffix glued to -i and accepts none; BSD sed requires a separate suffix argument, so it consumes the script as the suffix (the lab shows invalid command code f). The portable form is sed -i.bak 's/a/b/' file && rm file.bak. See Portability and sed.

7 — curl https://api/x returns an HTML 500 page but the script continues as if it worked. What do you add? Important ​

Answer

Answer: --fail (exit 22 for HTTP 400 and above; --fail-with-body if you want the body for the log), plus --silent --show-error, --connect-timeout, --max-time and --retry N for the transient codes (408, 429, 500, 502, 503, 504, 522, 524). Check $? or let set -e stop the script. See curl in scripts.

8 — Explain why trap 'rm -rf "$tmp"' EXIT is not enough for a robust cleanup, and what you add. Important ​

Answer

Answer: The EXIT trap does keep the original exit status unless the handler calls exit with another value, but a handler that runs other commands loses $? for its own logging, so capture rc=$? first and finish with exit "$rc"; also, it can re-enter if cleanup itself fails, it does not run on SIGKILL, and a signal that is not trapped may terminate the shell in a way you did not intend. Add rc=$? as the first line of the handler, trap - EXIT, then cleanup, then exit "$rc"; map INT, TERM and HUP to exit 130/143/129 so EXIT fires; accept that kill -9 leaves residue and use mktemp names in a directory a cleaner can sweep, or kernel-held locks. See trap.

9 — When is it time to rewrite a shell script in Go or Python? Must-know ​

Answer

Answer: When it passes roughly 100 lines, needs data structures or non-trivial control flow, parses structured formats beyond jq/yq, needs retries with backoff or concurrency, needs unit tests or runs where no shell exists (distroless images, Windows). Google's shell style guide says to rewrite early, because scripts grow. Keep shell for thin launchers (exec the binary) and for gluing programs. See When to switch.

10 — What is the difference between [ ] and [[ ]], and why does [ $x = y ] sometimes fail with "unary operator expected"? Important ​

Answer

Answer: [ is an ordinary command (POSIX), so its operands undergo word splitting and globbing: an empty unquoted $x disappears and the command becomes [ = y ]. [[ ]] is a bash/zsh/ksh keyword that does no splitting or globbing on its operands and adds == patterns, =~ regex and &&/||; it is not available in POSIX sh. Quote operands in [ ] or use [[ ]] where bash is guaranteed. See Control flow.

11 — Why do you pipe sort before uniq -c, and how do you list the top five client IPs in an access log? Important ​

Answer

Answer: uniq only merges adjacent identical lines, so equal lines must be adjacent first. cut -d' ' -f1 access.txt | sort | uniq -c | sort -rn | head -5 extracts the field, groups, counts, orders by count and keeps five. In awk the same is awk '{n[$1]++} END{for(k in n) print n[k], k}' access.txt | sort -rn | head -5. See The small tools and awk.

12 — Why must a Docker entrypoint script end with exec "$@", and what happens without it? Must-know ​

Answer

Answer: The container's PID 1 receives SIGTERM from docker stop or Kubernetes. Without exec the shell stays PID 1 and starts the service as a child; the shell neither forwards the signal nor exits, so the service never drains and is SIGKILLed after the grace period (Docker's stop timeout is 10 seconds for Linux containers; a Kubernetes Pod's grace period defaults to 30 seconds). exec replaces the shell with the service, which then receives the signal directly. See signals and the Go wrapper.

13 — artisan migrate --isolated returns 0 on a host, yet the migration did not run there. Is that a bug? Good to know ​

Answer

Answer: No, it is documented: with --isolated Laravel takes an atomic lock via the cache driver, and a process that cannot get the lock skips the command but still exits successfully. A deploy script that needs proof of migration must check the migration status afterwards or let exactly one designated host run it. See Laravel.

14 — Why parse a .env file with a loop instead of source .env, and where should production secrets live? Good to know ​

Answer

Answer: source executes the file as shell code, so a value with $(...), a backtick or an unquoted space can run commands or break parsing; a loop that splits at the first = and exports the value treats the file as data. Production secrets belong in a secret manager or a mounted file with mode 0600, delivered to the process by stdin or file, not in the repository, a command-line argument or set -x output. See Environment and secrets.

Glossary ​

TermMeaning
POSIX shThe portable shell command language standardised by POSIX (Issue 8 is IEEE Std 1003.1-2024)
bashThe GNU Bourne-Again shell; macOS ships 3.2.57, Linux usually 5.x
zshThe shell macOS has used as the default login shell since 10.15; no word splitting by default
dash / ashMinimal POSIX shells used as /bin/sh on Debian/Ubuntu and in BusyBox/Alpine
ShebangThe #!interpreter first line the kernel uses to run a script
Exit statusThe 0-255 number a command returns; 0 is success; $? holds the last one
set -e (errexit)Exit when a simple command fails, outside the exempt contexts
set -u (nounset)Treat expansion of an unset variable as an error
pipefailMake a pipeline's status the last non-zero stage's status
PIPESTATUSBash array with the exit status of every stage of the last pipeline
IFSInternal Field Separator: the characters used for word splitting and read
Word splittingDividing the result of an unquoted expansion into words at IFS characters
GlobbingExpanding *, ? and [...] to matching file names
Parameter expansion${var...} forms: defaults, length, trimming, substitution
Command substitution$(cmd): replaced by the command's output without trailing newlines
Process substitution<(cmd): a file name that streams a command's output (bash, zsh, ksh)
Here-document<<EOT: inline multi-line stdin; quoted delimiter disables expansion
File descriptorA small integer naming an open file: 0 stdin, 1 stdout, 2 stderr
2>&1Make fd 2 a duplicate of fd 1 at that point in the command line
teeCopies stdin to stdout and to files
xargsBuilds argument lists from stdin; -0 reads NUL-separated names
BRE / EREBasic and extended POSIX regular expressions; grep -E and sed -E select ERE
PCREPerl-compatible regex; grep -P on GNU only
sedStream editor; s/old/new/ substitution
awkField-oriented text language with associative arrays and an END block
jqA command-line JSON filter language
yqCommand-line YAML processor (mikefarah v4 uses jq-like syntax)
mktempCreates a unique temporary file or directory safely
trapRegisters a command to run on a signal or on exit
flockutil-linux command managing flock(2) advisory file locks
IdempotentSafe to run repeatedly with the same end result
Dry runA mode that prints intended actions without performing them
getoptsBuiltin that parses short command-line options
.env fileA KEY=VALUE text file for configuration, never committed with secrets
shellcheckStatic analyser for shell scripts (rules named SCnnnn)
shfmtShell formatter and parser from the mvdan/sh project
BatsBash Automated Testing System (bats-core)
BSD vs GNU userlandThe two families of Unix tools: macOS/FreeBSD versus Linux; flags differ
execReplace the shell process with a command (no fork)
SIGPIPESignal sent to a writer when the reader of a pipe has gone; status 141
Atomic renamerename(2) within one filesystem: readers see the old or the new file, never half

References ​

All URLs were fetched and saved under pipeline/sources/shell-scripting-text-processing/ (see manifest.tsv). The GNU sed, gawk, coreutils and findutils manuals were read from the unofficial GitHub mirrors of their Texinfo sources because www.gnu.org timed out from the build host for those pages.

Built by Morteza Negahi