Bash beyond the basics: expansions, arrays, here-documents and process substitution
Build version 1 of a log-report script step by step: the expansion order, defaults and required values with parameter expansion, string surgery without sed, indexed and associative arrays, nullglob, extglob and globstar, here-documents, here-strings and process substitution.
Contentsand lesson path
On this page
- The problem
- Step 1: Know the order in which Bash expands a line
- Step 2: Defaults and required values with parameter expansion
- Step 3: Cut and rewrite strings without starting sed
- Step 4: Keep file names in an array, count in an associative array
- Step 5: Globs that match nothing, and globs that go deeper
- Step 6: Help text from a here-document, input from a here-string
- Step 7: Compare two days with process substitution
- Step 8: Put it together
- Check your understanding
- Apply it
- Review prompt
Lessons of Advanced Shell & Text Processing
- Patterns that travel: regular expressions in grep, sed and awk Concept · 25 min
- Lab: from a raw access log to a report with grep, sed and awk Lab · 30 min
- Bash beyond the basics: expansions, arrays, here-documents and process substitution Worked example · 25 min
- When a script misbehaves: tracing, syntax checks, safe input and portability to dash Worked example · 20 min
- Lab: living on a remote server - editors, sudoedit, startup files, job control and tmux Lab · 30 min
- Check: shell fluency tasks and a log-report script to repair Knowledge check · 10 questions
What you will learn
- Use Bash expansions and data structures - parameter expansion for defaults, substrings, pattern replacement and case conversion, brace, arithmetic and pathname expansion, indexed and associative arrays, here-documents, here-strings and process substitution - in working scripts.
Prerequisites: Scripting Basics
01. The problem
The on-call team wants the pipelines from the access-log lab as one command for any server: logreport.sh -d DIR -n TOP. The constraints:
- Options must have sensible defaults, and environment variables (
LOGDIR,TOP) may override them. -hprints a help text that shows the real defaults.- The log directory may contain spaces (one server keeps logs in
web logs/), and some servers have no rotated files yet. - A bad option value must stop the script with a clear message and exit code 2, not produce a wrong report.
- It runs with Bash on Linux servers; it does not need to run under
/bin/sh(the next lesson deals with portability).
We build version 1 step by step, assuming the quoting and strict-mode habits from quoting, strict mode and ShellCheck. Run the blocks in the directory where you created logs/ in the lab, with bash 5.x (tested with 5.2.37 on Debian 13; the features used here also exist in 4.4 and later).
02. Step 1: Know the order in which Bash expands a line
Before Bash runs a command, it rewrites the words of the line in a fixed order. The Bash manual lists it as: brace expansion; then tilde, parameter, arithmetic expansion and command substitution, left to right; then word splitting; then pathname expansion (globbing); then quote removal. Process substitution happens in the same group as parameter expansion.
Two consequences explain most surprises. First, word splitting happens only to the results of unquoted expansions, and globbing to any unquoted word that contains *, ? or [, so "$x" stays one word and keeps its * literal. Second, brace expansion runs before variables have values, so it cannot use them. Predict the first line of output before you run the block.
x='logs/*.gz'; dir=logs
echo $x "$x"
echo {a,b}-$dir
n=3; echo file{1..3}.txt $((n * 2))logs/access.log-20261124.gz logs/access.log-20261125.gz logs/*.gz
a-logs b-logs
file1.txt file2.txt file3.txt 6Unquoted $x became the pattern logs/*.gz, and pathname expansion turned it into two file names; quoted, it stayed as typed. {a,b}-$dir first became a-$dir b-$dir, and only then did $dir expand. Keep this order in mind for every step below.
03. Step 2: Defaults and required values with parameter expansion
An option needs a default, and the default may come from the environment. Parameter expansion does this without an if:
${VAR:-word}useswordwhenVARis unset or empty, and leavesVARunchanged.${VAR:=word}does the same and also assignswordtoVAR.${VAR:?message}stops a non-interactive shell withmessagewhenVARis unset or empty.- Without the colon (
${VAR-word}), only unset counts; an empty value is kept.
The script uses dir=${LOGDIR:-./logs} because a user who exports LOGDIR= by mistake should still get the default, not an empty path.
unset OUT; echo "${OUT:-report.txt}"; echo "OUT is now '${OUT}'"
echo "${OUT:=report.txt}"; echo "OUT is now '${OUT}'"
EMPTY=''; echo "[${EMPTY:-dflt}] [${EMPTY-dflt}]"
cat > need.sh <<'EOF'
: "${LOGDIR:?set LOGDIR to the log directory}"
echo "not reached"
EOF
unset LOGDIR; bash need.sh; echo "rc=$?"report.txt
OUT is now ''
report.txt
OUT is now 'report.txt'
[dflt] []
need.sh: line 1: LOGDIR: set LOGDIR to the log directory
rc=1The here-document writes a two-line script, need.sh, and the last line runs it with LOGDIR unset. : does nothing; the line exists for its expansion. The :? expansion printed the message with the script name and line, and stopped the script with status 1 before echo "not reached". Run as a separate script, it leaves your terminal open; typed at an interactive prompt, :? aborts only that command.
04. Step 3: Cut and rewrite strings without starting sed
The help text should print the script name without its directory, and the report will need the date from a file name such as access.log-20261124.gz. Parameter expansion can remove a prefix (# shortest, ## longest), remove a suffix (% shortest, %% longest), take a substring (${s:offset:length}), replace a pattern (${s/old/new} once, ${s//old/new} everywhere) and change case (${s^^} upper, ${s,,} lower, ${s^} first letter). Each runs inside Bash and starts no extra process, which matters in loops.
f=logs/access.log-20261124.gz
echo "${f##*/} ${f%/*} ${f#*-} ${#f}"
d=${f##*-}; d=${d%.gz}; echo "${d:0:4}-${d:4:2}-${d:6:2}"
p='/api/orders/1842'; echo "${p//[0-9]/#} ${p/orders/carts}"
m='get'; echo "${m^^} ${m^}"; M='POST'; echo "${M,,}"access.log-20261124.gz logs 20261124.gz 27
2026-11-24
/api/orders/#### /api/carts/1842
GET Get
postThe patterns after #, % and / are glob patterns, not regular expressions: * means "any characters" and [0-9] one digit. That is why ${f#*-} cut up to the first dash. If you need a real regex, use [[ $s =~ regex ]] and read the groups from BASH_REMATCH, or hand the work to sed.
05. Step 4: Keep file names in an array, count in an associative array
A space-separated string cannot hold the name web logs/access.log safely: word splitting would cut it in two. An indexed array keeps each element intact: files=(…) fills it, "${files[@]}" (with the quotes) expands to one word per element, ${#files[@]} is the count and ${files[-1]} the last element.
For counting, Bash 4 and later have associative arrays, indexed by strings. They must be declared with declare -A before use; without it, Bash treats the array as indexed and evaluates the subscript as arithmetic. The loop reads its input through process substitution, < <(command), so that it runs in the current shell and the array is still filled after the loop.
files=(logs/access.log-*.gz logs/access.log)
echo "${#files[@]} files; first=${files[0]}; last=${files[-1]}"
printf '<%s>\n' "${files[@]}"
declare -A hits=()
while read -r ip _; do
hits[$ip]=$(( ${hits[$ip]:-0} + 1 ))
done < <(zcat -f "${files[@]}")
for ip in "${!hits[@]}"; do printf '%s %s\n' "${hits[$ip]}" "$ip"; done |
sort -k1,1nr -k2,23 files; first=logs/access.log-20261124.gz; last=logs/access.log
<logs/access.log-20261124.gz>
<logs/access.log-20261125.gz>
<logs/access.log>
7 203.0.113.7
6 192.0.2.55
5 198.51.100.23"${!hits[@]}" expands to the keys. Like awk, Bash does not promise any order for them, so the loop output goes through sort. read -r ip _ puts the first field in ip and the rest of the line in _, a throw-away name. For millions of lines, prefer the awk version from the lab, which does the whole loop in one process.
06. Step 5: Globs that match nothing, and globs that go deeper
By default, a glob that matches nothing stays as literal text, so a server with no .zst files would hand the string logs/*.zst to zcat. shopt -s nullglob makes such a glob expand to nothing instead. Two more options are useful: extglob adds patterns such as +([0-9]) (one or more digits) and !(*.gz) (anything except), and globstar makes ** match any depth of directories.
extglob changes how Bash parses a line, so it must be switched on before the line that uses it is read: put it on its own line near the top of the script.
shopt -s nullglob; none=(logs/*.zst); echo "zst files: ${#none[@]}"; shopt -u nullglob
none2=(logs/*.zst); echo "without nullglob: ${none2[0]}"
shopt -s extglob
echo logs/access.log-+([0-9]).gz; echo logs/!(*.gz)
mkdir -p deep/a/b; touch deep/a/b/x.log deep/y.log
shopt -s globstar; echo deep/**/*.logzst files: 0
without nullglob: logs/*.zst
logs/access.log-20261124.gz logs/access.log-20261125.gz
logs/access.log
deep/a/b/x.log deep/y.log07. Step 6: Help text from a here-document, input from a here-string
A here-document feeds the lines between <<WORD and a line containing only WORD to a command's standard input. With an unquoted WORD, variables and $(…) inside are expanded, which lets the help text show live defaults. With a quoted delimiter (<<'WORD'), the text is passed exactly as written. <<-WORD strips leading tab characters (not spaces) so the text can be indented inside a function. A here-string, <<< "text", feeds one string.
name=logreport
cat <<EOT
Usage: $name [-d DIR] [-n TOP]
-d DIR log directory (default: ${LOGDIR:-./logs})
EOT
cat <<'EOT'
literal: $name and $(date) stay as typed
EOT
read -r method path proto <<< 'GET /api/items HTTP/1.1'; echo "$method|$path|$proto"Usage: logreport [-d DIR] [-n TOP]
-d DIR log directory (default: ./logs)
literal: $name and $(date) stay as typed
GET|/api/items|HTTP/1.108. Step 7: Compare two days with process substitution
diff wants two files, but the data are the outputs of two pipelines. Process substitution, <(command), runs the command and gives its output a file name that the other command can open. The name is a path such as /dev/fd/63, a pipe the kernel exposes as a file. Here it shows which statuses differ between two days.
codes() { zcat "$1" | awk '{ print $(NF - 2) }' | sort -u; }
diff <(codes logs/access.log-20261124.gz) <(codes logs/access.log-20261125.gz)
echo "diff exit status: $?"
echo <(true)3,4c3,4
< 404
< 500
---
> 401
> 502
diff exit status: 1
/dev/fd/6309. Step 8: Put it together
Version 1 combines the steps; getopts parses -d, -n and -h. Read it with the constraints in mind:
[[ $top =~ ^[0-9]+$ ]]rejects a non-numeric-nbefore any work starts, with exit code 2 for "usage error".nullglobplus an explicit[[ -f … ]]test build the file list, so a directory without rotated files, or with no files at all, is handled on purpose."${files[@]##*/}"applies##*/to every element.- The per-status table uses the associative array from step 4; the top-clients list uses awk, because one awk process is the simpler tool for a sort-and-count.
cat > logreport.sh <<'EOF'
#!/usr/bin/env bash
# logreport.sh: summarise plain and gzipped access logs (version 1)
set -euo pipefail
shopt -s nullglob
usage() {
cat <<EOT
Usage: ${0##*/} [-d DIR] [-n TOP] [-h]
Summarise the access.log files in DIR (plain or .gz).
-d DIR log directory (default: ${LOGDIR:-./logs})
-n TOP clients to list (default: ${TOP:-3})
EOT
}
dir=${LOGDIR:-./logs}
top=${TOP:-3}
while getopts 'd:n:h' opt; do
case $opt in
d) dir=$OPTARG ;;
n) top=$OPTARG ;;
h) usage; exit 0 ;;
*) usage >&2; exit 2 ;;
esac
done
[[ $top =~ ^[0-9]+$ ]] || { echo "TOP must be a number, got '$top'" >&2; exit 2; }
files=("$dir"/access.log-*.gz) # rotated days, oldest first
[[ -f $dir/access.log ]] && files+=("$dir/access.log") # then today
(( ${#files[@]} > 0 )) || { echo "no access logs in $dir" >&2; exit 1; }
printf 'files: %s\n' "${files[@]##*/}"
declare -A per_status=()
while read -r status; do
per_status[$status]=$(( ${per_status[$status]:-0} + 1 ))
done < <(zcat -f -- "${files[@]}" | awk '{ print $(NF - 2) }')
for s in "${!per_status[@]}"; do
printf 'status %s: %d\n' "$s" "${per_status[$s]}"
done | sort
echo "top $top clients:"
zcat -f -- "${files[@]}" | awk '{ n[$1]++ } END { for (ip in n) print n[ip], ip }' |
sort -k1,1nr -k2,2 | awk -v n="$top" 'NR <= n'
EOF
chmod +x logreport.shmkdir -p 'web logs' && cp logs/access.log* 'web logs/'
./logreport.sh -d 'web logs' -n 2; echo "rc=$?"
./logreport.sh -d 'web logs' -n two; echo "rc=$?"
./logreport.sh -d /nonexistent; echo "rc=$?"files: access.log-20261124.gz
files: access.log-20261125.gz
files: access.log
status 200: 8
status 201: 3
status 400: 1
status 401: 2
status 404: 1
status 500: 2
status 502: 1
top 2 clients:
7 203.0.113.7
6 192.0.2.55
rc=0
TOP must be a number, got 'two'
rc=2
no access logs in /nonexistent
rc=1Status 400 is counted here, although the lab rejected that line: counting from the end of the line ($(NF - 2)) happens to work for it, but other fields would not, so validation belongs in version 2. With -n 0, what does the top-clients list print, and should the check reject it?
When should this stop being a Bash script? When it needs to parse JSON logs, keep state between runs or be tested function by function, porting it to Python is usually the better trade.
10. Check your understanding
11. Apply it
Turn version 1 into version 2, the skill's logreport.sh practice task. Add the validation from lab step 3, the per-hour status table and the slowest-endpoints table from lab steps 6 and 8, and a -o FILE option whose default comes from ${OUT:-report.csv}. Check with bash -n and ShellCheck before you run it, and keep version 1 to compare outputs on the same logs.
12. Review prompt
Without looking back, write the order in which Bash expands a command line, and use it to explain why "$x" keeps a * while $x does not, and why {1..$n} does not count to n. Then explain why the counting loop in step 4 reads from < <(…) and not from a pipe, and what declare -A changes.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.