You can now write solid, safe scripts. This lesson covers the features that separate a good Bash script from an expert one: comparing command output without temporary files, running work in parallel, indirect variables, smarter globbing, formatted output and a few built-in variables that save external calls. None of them are needed every day, but each one removes a whole category of clumsy workarounds.
In simple words
- Process substitution:
<(command)lets a command's output be used as if it were a file. - mapfile: reads lines from a file or command into an array in one step.
- Background jobs and wait: & runs work in parallel, and wait pauses until it all finishes.
- printf: prints formatted text. More reliable than echo.
Process substitution: <( )
Many tools only accept file names: diff, comm, paste, join. Process substitution runs a command and gives its output a temporary file name (like /dev/fd/63) that you can pass anywhere a file is expected.
Compare what is configured with what is running, without saving either to disk:
cp /etc/hosts hosts.newsed -i 's/10.0.2.10 db1/10.0.2.20 db2/' hosts.newdiff <(sort /etc/hosts) <(sort hosts.new)3c3< 10.0.2.10 db1---> 10.0.2.20 db2comm shows lines unique to each sorted input. With -3 it hides lines common to both:
comm -3 <(awk '{print $2}' /etc/hosts | sort) <(awk '{print $2}' hosts.new | sort)db1 db2The first column is only in the first input, the second (indented) only in the second. In real life this is how you answer "which pods are running that are not in the manifest?" or "which users exist on server A but not B?":
comm -23 <(kubectl get deploy -o name | sort) <(grep -h '^ name:' k8s/*.yaml | awk '{print "deployment.apps/" $2}' | sort)Feeding a loop without losing variables
You saw this in the loops lesson: cmd | while read runs the loop in a subshell, so counters are lost. < <(cmd) feeds the loop from process substitution and keeps it in the current shell:
total=0while read -r _ bytes; do total=$((total + bytes)); done < <(awk '{print $1, $10}' /var/log/nginx/access.log)echo "total bytes: $total"total bytes: 55046>( ) is the output version: tee >(gzip > out.gz) > out.txt writes compressed and plain copies at once.
mapfile with options
mapfile (lesson 7) has options worth knowing: -s N skips the first N lines (headers) and -n N reads at most N:
mapfile -t -s 1 rows < servers.csvecho "${#rows[@]} servers"printf ' %s\n' "${rows[@]:0:2}"5 servers web1,prod,10.0.1.10,4 web2,prod,10.0.1.11,4Running work in parallel: & and wait
Put & after a command to run it in the background. The script continues immediately; wait pauses until background jobs finish. $! is the process ID of the most recent background job.
#!/usr/bin/env bashcheck() { local host=$1 if ping -c 1 -W 2 "$host" > /dev/null; then echo "$host up"; else echo "$host DOWN"; fi} for h in web1 web2 db1 cache1; do check "$h" & # all four run at the same timedonewait # block until all of them finishecho "all checks done"Four 2-second checks take about 2 seconds instead of 8. To collect each job's exit code, remember the PIDs and wait for each one:
pids=()for h in "${hosts[@]}"; do deploy_to "$h" & pids+=($!)donefailed=0for pid in "${pids[@]}"; do wait "$pid" || failed=$((failed + 1))doneecho "$failed host(s) failed"Limiting parallelism
Starting 500 jobs at once can overload a machine or an API. Two common ways to cap it:
# xargs: run at most 8 at a time, one argument per jobprintf '%s\n' "${hosts[@]}" | xargs -P 8 -I{} ./check-host.sh {} # Bash: wait for any job to finish when 8 are running (Bash 4.3+)for h in "${hosts[@]}"; do while (( $(jobs -rp | wc -l) >= 8 )); do wait -n; done check "$h" &donewaitGNU parallel offers even more control (retries, progress, output grouping) if it is available.
Indirection and namerefs
Sometimes the name of a variable is in another variable, such as choosing settings per environment.
${!name} reads the variable whose name is stored in name:
prod_replicas=6staging_replicas=2env=prodvar="${env}_replicas"echo "${!var}"6${!prefix*} lists all variable names that start with a prefix:
APP_PORT=8080; APP_ENV=prod; APP_DEBUG=0for v in ${!APP_*}; do echo "$v=${!v}"; doneAPP_DEBUG=0APP_ENV=prodAPP_PORT=8080A nameref (declare -n) is a variable that is an alias for another. It is the clean way to let a function fill in a variable or array chosen by the caller:
set_default() { declare -n target=$1; [[ -n ${target:-} ]] || target=$2; }region=""set_default region ap-south-1echo "$region"ap-south-1Formatted output with printf
echo is fine for simple text, but printf gives precise, portable formatting. It reuses the format for extra arguments, which makes tables easy:
printf '%-10s %-8s %5s\n' NAME ENV CPUwhile IFS=, read -r n e _ c; do printf '%-10s %-8s %5d\n' "$n" "$e" "$c"; done < <(tail -n +2 servers.csv)printf '%s\n' one two threeprintf -v stamp '%(%F)T' -1printf -v padded '%05d' 42echo "$padded"NAME ENV CPUweb1 prod 4web2 prod 4db1 prod 8web-stg staging 2ci-runner tools 16onetwothree00042%-10sis a string left-aligned in 10 characters;%5dan integer right-aligned in 5.printf -v varstores the result in a variable instead of printing (no subshell needed).${var@Q}quotes a value so it can be safely reused as shell input, which is useful when logging commands:echo "running: ${cmd@Q}".
Smarter globbing with shopt
shopt turns on optional shell behaviour. Three options fix real annoyances:
shopt -s nullglobfor f in /var/log/*.gz; do echo "found $f"; doneecho "no .gz files, and the loop body never ran"shopt -s globstarfor f in /var/log/**/*.log; do echo "$f"; doneno .gz files, and the loop body never ran/var/log/app/app.log/var/log/nginx/access.lognullglob: a pattern that matches nothing expands to nothing, instead of staying as the literal text*.gz. That removes the[[ -e $f ]] || continuecheck from loops.globstar:**matches any number of subfolders, so**/*.logfinds log files at any depth withoutfind.extglob: extended patterns such as!(*.log)(everything except.logfiles) and+(a|b).
Turn on what a script needs right at the top, next to set -euo pipefail.
Built-in variables that save external commands
| Variable | Value |
|---|---|
$SECONDS | seconds since the shell (or script) started; assign 0 to reset |
$RANDOM | random integer 0–32767 |
$BASHPID | PID of the current (sub)shell; $$ stays the main script's PID |
$PIPESTATUS | array of exit codes from the last pipeline |
$BASH_SOURCE, $LINENO, $FUNCNAME | where you are, for logs and traces |
$EPOCHSECONDS | Unix time, without calling date |
SECONDS=0sleep 2echo "step took ${SECONDS}s"Timing a whole command is even easier with the time keyword:
time grep -c ERROR /var/log/app/app.log2real 0m0.012suser 0m0.004ssys 0m0.003sReal-world scenario: a fleet-wide config drift check
A team manages 40 servers that should all have identical /etc/nginx/nginx.conf. A nightly job fetches each server's config in parallel and compares it with the version in git:
#!/usr/bin/env bashset -euo pipefailshopt -s nullglobmapfile -t hosts < <(grep -v '^#' inventory.txt)tmp=$(mktemp -d); trap 'rm -rf "$tmp"' EXIT for h in "${hosts[@]}"; do ssh -o ConnectTimeout=5 "$h" cat /etc/nginx/nginx.conf > "$tmp/$h.conf" 2>/dev/null &donewait drift=0for h in "${hosts[@]}"; do if ! diff -q "$tmp/$h.conf" repo/nginx.conf > /dev/null; then echo "DRIFT on $h:" diff -u repo/nginx.conf "$tmp/$h.conf" | head -n 20 drift=$((drift + 1)) fidoneprintf 'checked %d hosts in %ds, %d drifted\n' "${#hosts[@]}" "$SECONDS" "$drift"exit "$drift"Parallel ssh with &/wait makes 40 hosts take seconds, mapfile loads the inventory safely, diff -u shows exactly what changed, and $SECONDS reports the runtime for free.
Common mistakes
- Forgetting
wait: the script exits while background jobs are still running, and their output appears later or is lost. - Unlimited parallelism against shared systems; cap it with
xargs -Porwait -n. - Using
evalto build variable names; use${!name}ordeclare -ninstead, which cannot run arbitrary code. - Turning on
nullglobglobally in an interactive shell:ls *.nothingthen lists the current folder. Use it in scripts. - Expecting process substitution in
sh: it is a Bash feature (see the next lesson).
Practice
- Use
diff <( ) <( )to compare the user names in/etc/passwdwith a copy where you deleted one user. - Total the CPU column of
servers.csvwithwhile read … done < <(…)and print the result after the loop. - Start three
sleep 1commands in the background,waitfor them, and print$SECONDSto show they ran together. - Store
dev_url,staging_urlandprod_urlvariables and print the one chosen byenvusing${!var}. - Print
servers.csvas an aligned table withprintf.
Cheat sheet
diff <(cmd1) <(cmd2) compare outputscomm -3 <(sort a) <(sort b) lines unique to eachwhile …; done < <(cmd) loop keeps its variablescmd & $! wait wait "$pid" background jobsxargs -P 8 -I{} cmd {} cap parallelism${!name} ${!prefix*} indirectiondeclare -n ref=$1 namerefprintf '%-10s %5d\n' "$s" "$n" formattingprintf -v var '%05d' 7 format into a variable${var@Q} shell-quoted valueshopt -s nullglob globstar safer, recursive globsSECONDS=0 … $SECONDS elapsed timetime cmd time one commandmapfile -t -s 1 rows < f.csv skip headerKey takeaways
- Process substitution turns command output into a file name, so
diff,command loops work without temp files. &andwaitrun independent work in parallel; alwayswait, and cap parallelism for shared systems.${!name}anddeclare -nhandle variable names stored in variables, withouteval.printfformats tables and values precisely;printf -vstores the result.nullglobandglobstarmake globbing safe and recursive; built-in variables like$SECONDSreplace external calls.