Skip to content
$ lynuxpro
← Bash Scripting

LESSON 15 OF 17 · EXPERT · 20 MIN

Advanced Bash features

HOW IT WORKSAdvanced Bash: no temp files needed

kubectl get podslist Acat expected.txtlist B<( … )process substitutiondiff / commcomparemapfile -tlines → arrayjobs & waitrun in parallel
1/4

<( command ) runs a command and hands its output to another program as if it were a file.

diff <(sort live.txt) <(sort expected.txt)

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)
SHELLbashutf-8 · 3L
3c3< 10.0.2.10 db1---> 10.0.2.20 db2
OUTPUTterminalutf-8 · 4L

comm 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)
SHELLbashutf-8 · 1L
db1	db2
OUTPUTterminalutf-8 · 2L

The 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)
SHELLbashutf-8 · 1L

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"
SHELLbashutf-8 · 3L
total bytes: 55046
OUTPUTterminalutf-8 · 1L

>( ) 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}"
SHELLbashutf-8 · 3L
5 servers  web1,prod,10.0.1.10,4  web2,prod,10.0.1.11,4
OUTPUTterminalutf-8 · 3L

Running 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"
SHELLbashutf-8 · 11L

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"
SHELLbashutf-8 · 9L

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" &donewait
SHELLbashutf-8 · 9L

GNU 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}"
SHELLbashutf-8 · 5L
6
OUTPUTterminalutf-8 · 1L

${!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}"; done
SHELLbashutf-8 · 2L
APP_DEBUG=0APP_ENV=prodAPP_PORT=8080
OUTPUTterminalutf-8 · 3L

A 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"
SHELLbashutf-8 · 4L
ap-south-1
OUTPUTterminalutf-8 · 1L

Formatted 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"
SHELLbashutf-8 · 6L
NAME       ENV        CPUweb1       prod         4web2       prod         4db1        prod         8web-stg    staging      2ci-runner  tools       16onetwothree00042
OUTPUTterminalutf-8 · 10L
  • %-10s is a string left-aligned in 10 characters; %5d an integer right-aligned in 5.
  • printf -v var stores 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"; done
SHELLbashutf-8 · 5L
no .gz files, and the loop body never ran/var/log/app/app.log/var/log/nginx/access.log
OUTPUTterminalutf-8 · 3L
  • nullglob: a pattern that matches nothing expands to nothing, instead of staying as the literal text *.gz. That removes the [[ -e $f ]] || continue check from loops.
  • globstar: ** matches any number of subfolders, so **/*.log finds log files at any depth without find.
  • extglob: extended patterns such as !(*.log) (everything except .log files) 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

VariableValue
$SECONDSseconds since the shell (or script) started; assign 0 to reset
$RANDOMrandom integer 0–32767
$BASHPIDPID of the current (sub)shell; $$ stays the main script's PID
$PIPESTATUSarray of exit codes from the last pipeline
$BASH_SOURCE, $LINENO, $FUNCNAMEwhere you are, for logs and traces
$EPOCHSECONDSUnix time, without calling date
SECONDS=0sleep 2echo "step took ${SECONDS}s"
SHELLbashutf-8 · 3L

Timing a whole command is even easier with the time keyword:

time grep -c ERROR /var/log/app/app.log
SHELLbashutf-8 · 1L
2real	0m0.012suser	0m0.004ssys	0m0.003s
OUTPUTterminalutf-8 · 5L

Real-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"
SHELLbashutf-8 · 21L

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 -P or wait -n.
  • Using eval to build variable names; use ${!name} or declare -n instead, which cannot run arbitrary code.
  • Turning on nullglob globally in an interactive shell: ls *.nothing then lists the current folder. Use it in scripts.
  • Expecting process substitution in sh: it is a Bash feature (see the next lesson).

Practice

  1. Use diff <( ) <( ) to compare the user names in /etc/passwd with a copy where you deleted one user.
  2. Total the CPU column of servers.csv with while read … done < <(…) and print the result after the loop.
  3. Start three sleep 1 commands in the background, wait for them, and print $SECONDS to show they ran together.
  4. Store dev_url, staging_url and prod_url variables and print the one chosen by env using ${!var}.
  5. Print servers.csv as an aligned table with printf.

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 header
OUTPUTterminalutf-8 · 14L

Key takeaways

  • Process substitution turns command output into a file name, so diff, comm and loops work without temp files.
  • & and wait run independent work in parallel; always wait, and cap parallelism for shared systems.
  • ${!name} and declare -n handle variable names stored in variables, without eval.
  • printf formats tables and values precisely; printf -v stores the result.
  • nullglob and globstar make globbing safe and recursive; built-in variables like $SECONDS replace external calls.