Shell Scripting and Automation Questions
Shell-language craft for operations work: Bash and POSIX sh scripting, pipes and redirection, quoting and word splitting, exit codes and set -euo pipefail (including failures inside pipelines), traps and cleanup, argument parsing with getopts, functions and arrays, parameter expansion, here-documents, and text processing with grep, sed, awk and jq, including streaming pipelines over very large log, CSV and JSON Lines files. Also covers writing robust, idempotent, portable scripts (locking, atomic file updates, retries with backoff, safe temp files, GNU versus BSD differences), background jobs and signals, bounded parallelism and SSH fan-out, cron-driven jobs such as log rotation, backups, atomic deploys and health-check watchdogs, secure scripting (eval injection, secrets, path traversal), and debugging, testing and linting shell with ShellCheck and bats. Boundary: general automation design and Python or Go tooling, Linux host administration tasks, observability and alerting design, security detection engineering, and generic algorithmic coding problems are covered elsewhere.
An audit flagged world-writable files. Write a script that finds the regular files under /var, excluding symlinks and pseudo-filesystems, records their current permissions, and tightens them. How do you make the change reviewable and reversible?
Sample Answer
Direct answer
Split the work into three separate commands so each step can be reviewed and undone: scan (find the files and write a manifest of their current modes, changing nothing), apply (read only that reviewed manifest and clear just the world-write bit with chmod), and rollback (put each recorded mode back). The manifest is the review artifact and the undo log in one file. The scan uses -type f so symlinks are never matched, and -xdev so find stays on the filesystem it started on and never descends into mounted pseudo or network filesystems.
Reading the numbers and the key lines first
Mode. A file's permission mode is written in octal (base 8). Each of the last three digits belongs to one party, in the order owner, group, other, and is a sum of read = 4, write = 2, execute = 1. So 6 is 4 + 2 (read and write), 5 is 4 + 1 (read and execute), 7 is all three. 666 therefore means read and write for everyone, and 664 means read and write for owner and group but read only for other. "World-writable" means the other digit contains the 2.
Special bits. An optional fourth leading digit holds extra bits: 4 is setuid (when the file is a program it runs with its owner's privileges, not the caller's), 2 is setgid (the same for the group), 1 is the sticky bit (on a directory, only a file's owner may delete or rename entries in it, which is why /var/tmp is 1777). So 4757 is: setuid, owner 7 (rwx), group 5 (r-x), other 7 (rwx). World-write is the 2 inside that last 7, and removing it gives 4755.
The selector -perm -0002. -perm MODE matches an exact mode, while -perm -MODE (with the leading minus) matches files that have all the bits in MODE set, whatever else is set. 0002 is the other-write bit alone, so the test means "other-write is on".
The record format -printf '%m\t%u:%g\t%p\0'. %m is the mode in octal, %u the owner name, %g the group name, %p the path, \t a tab and \0 a NUL byte that ends the record. A manifest is simply the file holding one such record per candidate: the plan and the undo log.
The arithmetic new=$(printf '%o' $(( 8#$mode & ~8#002 ))). Read it from the inside out: 8#$mode tells the shell to read the digits as octal; ~8#002 flips every bit of 002, giving a mask in which every bit is 1 except the other-write bit; & keeps only the bits set on both sides, so the other-write bit is cleared and nothing else changes; printf '%o' prints the result back in octal. In binary the last three digits of 666 are 110 110 110, and clearing the final 2 gives 110 110 100, which is 664.
want and new in walk. mode is the mode recorded by the scan and new is that mode with other-write cleared. want is the mode the file must have right now for the script to touch it: during apply the file should still have the recorded mode, during rollback it should have the cleared new mode. Anything else is skipped.
-prune and sort -z. -prune tells find not to descend into a matching directory, and -o means "or", so the pruning branch handles those two directories and the rest of the expression applies to everything else. sort -z sorts records that end in NUL instead of newline.
A small tree with modes 666, 664, 662, 644 and 4757 shows each piece (run in an Ubuntu 24.04 container):
cd "$(mktemp -d)"
for m in 666 664 662 644 4757; do install -m $m /dev/null f$m; done
echo '--- -perm -0002 (all listed bits must be set)'
find . -type f -perm -0002 -printf '%m %p\n' | sort
echo '--- -perm 0002 (exact mode match)'
find . -type f -perm 0002 -printf '%m %p\n' | sort
echo '--- one record as written by -printf'
find . -name f4757 -printf '%m\t%u:%g\t%p\0' | tr '\0\t' '\n|'
echo
echo '--- the mode arithmetic'
for mode in 666 664 4757; do
printf '%s -> %o\n' "$mode" $(( 8#$mode & ~8#002 ))
done
--- -perm -0002 (all listed bits must be set)
4757 ./f4757
662 ./f662
666 ./f666
--- -perm 0002 (exact mode match)
--- one record as written by -printf
4757|root:root|./f4757
--- the mode arithmetic
666 -> 664
664 -> 664
4757 -> 4755
Reading it: the minus form matches 666, 662 and 4757, because each has other-write set, and skips 664 and 644. The exact form matches nothing, since no file has mode 0002. The record is mode, owner and group, then path, separated by tabs (shown here as |). A file already at 664 is left at 664, so clearing the bit is safe to repeat.
The script
GNU find, stat and chmod are assumed (Linux). Records are NUL-terminated and tab-separated, so a path containing spaces, a tab in the middle of the name, or even a newline survives the round trip. One limit: read strips tab characters at the very end of the last field, so a file whose name ends in a tab is reported as SKIP (not a regular file now) and left alone (a safe failure, not a wrong chmod); such names should be fixed by hand.
#!/usr/bin/env bash
# ww.sh scan ROOT MANIFEST | apply MANIFEST | rollback MANIFEST
set -euo pipefail
scan() {
local root=${1%/} manifest=$2
# -xdev: stay on ROOT's filesystem (skips mounted pseudo/network filesystems)
# -type f: regular files only, so symlinks are never matched
find "$root" -xdev \
\( -path "$root/lib/docker" -o -path "$root/lib/containers" \) -prune -o \
-type f -perm -0002 -printf '%m\t%u:%g\t%p\0' | sort -z > "$manifest"
printf 'scan: %d candidate(s) written to %s\n' \
"$(tr -cd '\0' < "$manifest" | wc -c)" "$manifest"
}
# Walk the manifest and apply or roll back each record whose mode still matches
walk() {
local manifest=$1 action=$2 mode owner path now want new
while IFS=$'\t' read -r -d '' mode owner path; do
new=$(printf '%o' $(( 8#$mode & ~8#002 )))
if [[ $action == apply ]]; then want=$mode; else want=$new; fi
if [[ ! -f $path || -L $path ]]; then
printf 'SKIP (not a regular file now): %s\n' "$path"; continue
fi
now=$(stat -c '%a' -- "$path")
if [[ $now != "$want" ]]; then
printf 'SKIP (mode is %s, expected %s): %s\n' "$now" "$want" "$path"; continue
fi
if [[ $action == apply ]]; then
chmod o-w -- "$path"; printf 'APPLY %s -> %s (%s) %s\n' "$mode" "$new" "$owner" "$path"
else
chmod -- "$mode" "$path"; printf 'ROLLBACK %s -> %s (%s) %s\n' "$new" "$mode" "$owner" "$path"
fi
done < "$manifest"
}
case ${1:-} in
scan) scan "${2:?ROOT}" "${3:?MANIFEST}" ;;
apply) walk "${2:?MANIFEST}" apply ;;
rollback) walk "${2:?MANIFEST}" rollback ;;
*) echo "usage: $0 scan ROOT MANIFEST | apply MANIFEST | rollback MANIFEST" >&2; exit 2 ;;
esac
Why each choice
-xdevis the pseudo-filesystem exclusion: every mount point below/var(tmpfs, NFS, overlay mounts,/var/lib/nfs/rpc_pipefsand similar) is skipped. If/varis itself a separate partition it is still scanned, because-xdevonly refuses to cross into a different filesystem than the starting point's.-type fmatches regular files only. A symlink is a different file type, so it is never listed, andchmodnever has a chance to follow one into another directory. Directories are excluded on purpose: a world-writable directory with the sticky bit (/var/tmpis1777) is by design and needs its own policy.-pruneof/var/lib/dockerand/var/lib/containers: files inside container image layers carry modes the image author chose, and changing them from the host is not part of this audit finding. Treat that as a decision to record in the ticket, not a silent skip.chmodclears only the other-write bit (mode & ~002, spelledo-win theapplycall), it does not force644. Group bits and the owner's access stay as they were, so a shared group workflow keeps working and the change is exactly what the auditor flagged. Setuid and setgid bits are preserved:4757becomes4755, not755.- Guards at apply time: each record is only touched if the path is still a regular file (not a symlink) and its mode still equals the recorded one. If someone changed it after the scan, the script skips it and says so rather than overwriting the newer decision.
- Rollback checks the other direction: it restores a recorded mode only if the file is still in the post-change mode, so running rollback twice, or after another admin edited the file, does not clobber anything.
Worked example
Run in a Debian-family Linux container (the --tmpfs flag mounts a separate tmpfs at /demo/var/mnt, to prove -xdev skips it). Save the script above as ww.sh and the demo below as demo.sh in one directory; the container sees both under /w. The demo creates a file with a space in its name, a file whose name contains a newline, a setuid world-writable file, a symlink pointing at a world-writable file, a group-writable file that must not be touched, and a world-writable file on the separate mount.
docker run --rm --tmpfs /demo/var/mnt -v "$PWD":/w ubuntu:24.04 bash /w/demo.sh
set -euo pipefail
mkdir -p /demo/var/{lib,spool,mnt}
cd /demo/var
install -m 666 /dev/null 'lib/app state.db'
install -m 664 /dev/null 'lib/group-writable.conf'
install -m 666 /dev/null "spool/odd
name"
install -m 4757 /dev/null lib/helper
ln -s '/demo/var/lib/app state.db' spool/link-to-state
install -m 666 /dev/null mnt/on-other-fs # mnt is a separate tmpfs
cd /
echo '--- scan'
bash /w/ww.sh scan /demo/var /demo/manifest.tsv
tr '\0' '\n' < /demo/manifest.tsv | cat -A | sed 's/\^I/ | /g'
echo '--- apply'
bash /w/ww.sh apply /demo/manifest.tsv
stat -c '%a %n' /demo/var/lib/* | sort
echo '--- rollback'
bash /w/ww.sh rollback /demo/manifest.tsv
echo '--- rollback again (idempotent)'
bash /w/ww.sh rollback /demo/manifest.tsv
Output:
--- scan
scan: 3 candidate(s) written to /demo/manifest.tsv
4757 | root:root | /demo/var/lib/helper$
666 | root:root | /demo/var/lib/app state.db$
666 | root:root | /demo/var/spool/odd$
name$
--- apply
APPLY 4757 -> 4755 (root:root) /demo/var/lib/helper
APPLY 666 -> 664 (root:root) /demo/var/lib/app state.db
APPLY 666 -> 664 (root:root) /demo/var/spool/odd
name
4755 /demo/var/lib/helper
664 /demo/var/lib/app state.db
664 /demo/var/lib/group-writable.conf
--- rollback
ROLLBACK 4755 -> 4757 (root:root) /demo/var/lib/helper
ROLLBACK 664 -> 666 (root:root) /demo/var/lib/app state.db
ROLLBACK 664 -> 666 (root:root) /demo/var/spool/odd
name
--- rollback again (idempotent)
SKIP (mode is 4757, expected 4755): /demo/var/lib/helper
SKIP (mode is 666, expected 664): /demo/var/lib/app state.db
SKIP (mode is 666, expected 664): /demo/var/spool/odd
name
Reading it: the manifest holds exactly three records (the file on the tmpfs, the symlink and the 664 file are absent). apply turned 666 into 664 and 4757 into 4755. rollback restored all three. The second rollback skipped everything because the modes no longer matched the "post-change" state, so it is safe to repeat. The scan writes .tsv records with the mode as its first field; sort -z orders them as byte strings, which is why 4757 sorts before 666.
Making it reviewable and reversible in practice
- Run
scan, attach the manifest to the change ticket, and store itssha256sumthere so reviewers knowapplyis working from the file they approved. - Triage the list before applying. Group by owning package (
rpm -Vordpkg --verifyreport files whose mode differs from what the package shipped) and by application: a few files in/var/liband/var/spoolare deliberately world-writable for a legacy service, and those need an application fix, not a blanketchmod. - Apply in a maintenance window, then re-run
scanagainst a fresh manifest path: the expected result is zero candidates other than the documented exceptions. - Keep the manifest for as long as the change can be disputed. Rollback needs it.
Trade-offs and pitfalls
- Race window. Between the
-Lcheck andchmoda local attacker who controls the directory could swap in a symlink.applyrunschmod o-w, which can only remove the other-write bit from whatever it lands on, rather than setting the absolute mode from the manifest, so a swapped-in symlink cannot be handed a setuid bit or any wider mode.rollbackdoes set an absolute mode, so it does add permissions: run it only on a quiet host and inspect the manifest first. - Extended attributes and ACLs (access control lists, per-user permission entries) are not captured by the mode alone. If the host uses them, add
getfacl -Routput to the review bundle. - A manifest is a point-in-time record. Files created after the scan are not covered, so schedule the scan as a recurring check and fix the writer (for example an application's
umask, the default permission mask), or the finding returns. - Do not "just run
find /var -perm -002 -exec chmod 644 {} +": it follows no review step, discards group and setuid bits, can reach symlinked targets via-Lhabits, and leaves nothing to undo it from.
A production shell script fails only under heavy load. How would you reproduce it, trace it and fix the race or resource-starvation cause?
Sample Answer
Direct answer
Work in this order. First, collect facts from the failure that already happened (exit status, the exact message, what else was running). Second, reproduce it on purpose: run many copies at once and add CPU load or tighter limits until it fails on demand. Third, trace the failing run with bash -x and with strace to see the order in which things really happened. Fourth, classify the cause: almost always either a race (two things touching the same file, lock or state, with a gap between the check and the action) or resource starvation (the process hit a limit on processes, file descriptors, memory or disk). Fifth, fix the cause (make the check-and-act atomic, or bound concurrency and raise the limit deliberately), then prove it with a repeated stress run, because one clean run proves nothing about a failure that is intermittent.
1. Facts from the real failure
- The exit status and the exact text on stderr. A few messages identify the class at once:
Cannot fork,fork: retry: Resource temporarily unavailable(process limit),Too many open files(descriptor limit),No space left on device(disk full, or out of inodes, the per-file records a filesystem has a fixed supply of),Killedwith no message (often the kernel's out-of-memory killer; checkdmesg -T | grep -i -E 'oom|killed process'). - What else ran at the same moment: other cron jobs, a second instance of the same script, a backup. Failures that appear under load often are two instances overlapping.
- For a process that is still alive, its limits and usage:
cat /proc/<pid>/limitsandls /proc/<pid>/fd | wc -l.
2. Reproduce it on demand
Start many copies at once, and add background CPU load so the scheduler interleaves them unfavourably. For example:
for i in $(seq "$(nproc)"); do yes > /dev/null & done # CPU hogs; kill them afterwards
for i in $(seq 20); do ./job.sh "$i" & done; wait # concurrent instances
To test starvation, lower the limit instead of waiting for the load. ulimit -n 12 caps the number of open file descriptors (the small numbers the kernel hands a process for each open file, pipe or socket) at 12 for that shell and its children, so run it in a subshell. docker run --pids-limit 20 caps a container at 20 processes. A small tmpfs (a size-limited filesystem held in memory) gives you a disk that fills quickly.
A race, reproduced
This script means "if there is no lock file, create one and do the job":
#!/usr/bin/env bash
# Check-then-act: "if no lock file, create it and do the job".
lock=${TMPDIR:-/tmp}/job.lock
if [ ! -e "$lock" ]; then
sleep 0.2 # stands in for load: the gap between check and create widens
touch "$lock"
echo "instance $1: running the job"
else
echo "instance $1: skipped, lock exists"
fi
The sleep 0.2 stands in for load: it makes the gap between the check and the create wide enough to hit every time. The two fixes. safe.sh uses mkdir, which either creates the directory or fails in one indivisible step, so exactly one instance wins:
#!/usr/bin/env bash
# mkdir either creates the directory or fails, in one step, so only one instance wins.
lock=${TMPDIR:-/tmp}/job.lock.d
if mkdir "$lock" 2>/dev/null; then
sleep 0.2
echo "instance $1: running the job"
else
echo "instance $1: skipped, lock exists"
fi
flock.sh asks the kernel for an exclusive lock on a file descriptor (exec 9>"$lock" opens the lock file as descriptor 9; flock -n 9 takes the lock or fails at once without waiting). The kernel releases it when the process exits, even if it was killed:
#!/usr/bin/env bash
# flock -n takes an exclusive lock on descriptor 9 or fails at once; the kernel drops it when the process exits.
lock=${TMPDIR:-/tmp}/job.lock
exec 9>"$lock"
if flock -n 9; then
sleep 0.2
echo "instance $1: running the job"
else
echo "instance $1: skipped, lock exists"
fi
Running five copies at once against these three variants printed:
racy.sh: 5 of 5 simultaneous instances ran the job
safe.sh: 1 of 5 simultaneous instances ran the job
flock.sh: 1 of 5 simultaneous instances ran the job
The script that drives the experiment starts the five copies as background jobs (&), waits for all of them, then counts how many printed running the job. It gives each variant a clean lock first:
export TMPDIR=$PWD/tmp; rm -rf "$TMPDIR"; mkdir "$TMPDIR"
for s in racy safe flock; do
rm -rf "$TMPDIR"/job.*
ran=$( { for i in 1 2 3 4 5; do bash "$s.sh" "$i" & done; wait; } | grep -c 'running the job')
echo "$s.sh: $ran of 5 simultaneous instances ran the job"
done
3. Trace it
bash -x prints each command as it runs. PS4 (the prefix of those trace lines) can carry the script name and line number. Set PS4 inside the shell that runs the trace; an exported PS4 was ignored by the child bash in this test. The backslashes in \$ matter: they store the literal text ${BASH_SOURCE##*/} and ${LINENO} in PS4, so bash evaluates them again for each traced line instead of once when PS4 is assigned (without them every line shows the line number of the assignment, :1). source racy.sh 1 runs the script inside the wrapper shell, which is why the first line has an empty file name (the wrapper itself has no source file) and why the commands from the script carry ++: one + per level of nesting.
bash -c 'PS4="+ \${BASH_SOURCE##*/}:\${LINENO} "; set -x; source racy.sh 1'
+ :1 source racy.sh 1
++ racy.sh:3 lock=/w/tmp/job.lock
++ racy.sh:4 '[' '!' -e /w/tmp/job.lock ']'
++ racy.sh:5 sleep 0.2
++ racy.sh:6 touch /w/tmp/job.lock
++ racy.sh:7 echo 'instance 1: running the job'
instance 1: running the job
Lines 4 to 6 are the check ([ ! -e ... ] is the traced form of the if test), the pause and the create. To see the length of the gap, put $EPOCHREALTIME (the current time in seconds with microseconds, bash 5) in PS4 as well:
bash -c 'PS4="+ \$EPOCHREALTIME \${BASH_SOURCE##*/}:\${LINENO} "; set -x; source racy.sh 1'
+ 1791273620.746685 :1 source racy.sh 1
++ 1791273620.746842 racy.sh:3 lock=/w/tmp/job.lock
++ 1791273620.746859 racy.sh:4 '[' '!' -e /w/tmp/job.lock ']'
++ 1791273620.746942 racy.sh:5 sleep 0.2
++ 1791273620.957567 racy.sh:6 touch /w/tmp/job.lock
++ 1791273620.959567 racy.sh:7 echo 'instance 1: running the job'
instance 1: running the job
The time stamps differ on every run. The jump from ...620.746942 to ...620.957567 is about 0.21 seconds: that is the window, from the check on line 4 to the create on line 6, in which another instance can also pass the check.
strace (a tool that logs system calls) shows the same thing from the operating system's side, across child processes (-f) with timestamps (-tt). Filtering to the lock path:
strace -f -tt -e trace=newfstatat,openat -o st.txt bash racy.sh 1; grep job.lock st.txt
newfstatat(AT_FDCWD, "/srv/demo/tmp/job.lock", 0xffffe6926978, 0) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/srv/demo/tmp/job.lock", O_WRONLY|O_CREAT|O_NOCTTY|O_NONBLOCK, 0666) = 3
(Process ids and timestamps, which strace puts at the start of each line, are omitted; the address in the first line differs per run, and the exact name of the status call varies with the system.) Reading it: newfstatat asks the kernel about the file's status (AT_FDCWD means "relative to the current directory"), and it returns -1 ENOENT, "no such file or directory", so the check finds nothing. openat with O_CREAT then creates the file and returns descriptor 3. Two separate system calls, a check that finds nothing and a create, with time between them in which any other process can do the same. That is a time-of-check to time-of-use race (TOCTOU): the answer to the check is stale by the time the action runs.
Starvation, reproduced
limits.sh takes a mode: fds lowers the descriptor limit to 12 and keeps opening files, procs launches 40 background sleep processes:
#!/usr/bin/env bash
# Starvation demo. usage: limits.sh fds | limits.sh procs
dir=${TMPDIR:-/tmp}
case $1 in
fds) ulimit -n 12
for i in $(seq 1 20); do
exec {fd}>"$dir/f$i" || { echo "open #$i failed"; break; }
done ;;
procs) for i in $(seq 1 40); do sleep 5 & done; wait ;;
esac
exec {fd}>file opens the file on a fresh descriptor number (10 or higher) that bash picks and stores in $fd, and it never closes it, which is exactly a descriptor leak. The first three lines of output of bash limits.sh fds, then the first three of bash limits.sh procs run in a container started with --pids-limit 20:
--- file descriptors
limits.sh: redirection error: cannot duplicate fd: Too many open files
limits.sh: line 7: /w/tmp/f3: Too many open files
open #3 failed
--- processes
limits.sh: fork: retry: Resource temporarily unavailable
limits.sh: fork: retry: Resource temporarily unavailable
limits.sh: fork: retry: Resource temporarily unavailable
The first two files opened, on descriptors 10 and 11; the third failed because the limit of 12 allows descriptors 0 to 11 only, and exec {fd}> takes numbers from 10 upward, so 10 and 11 were the only ones it could use. The word retry is bash trying the fork again before it gives up, so a script under process pressure can stall or fail only when the host is busy.
4. Classify and fix
| What you see | Likely cause | Fix |
|---|---|---|
| Two instances both "win" a check | Check-then-act (`[ -e f ] | |
| Wrong data in a shared file or a temp file clobbered | Fixed temp names such as /tmp/out.$$ or /tmp/out, or concurrent read-modify-write | mktemp for private files; mv a finished file into place (rename is atomic); a lock around read-modify-write |
| Works when idle, hangs or fails when busy | sleep 5 used to wait for another process | Wait for the condition itself: poll for the file or port with a timeout, or wait for the child |
fork: retry, Cannot fork | Unbounded background jobs hit a process limit | Bound concurrency (xargs -P N, or wait -n in a loop), then raise the limit only if N is justified |
Too many open files | Descriptors leaked in a loop (opened, never closed) or a low ulimit -n | Close descriptors (exec {fd}>&-), or raise LimitNOFILE or ulimit -n for the service |
| Truncated or interleaved output | Many writers appending to one file with large writes | One writer, or flock around the append, or one file per writer |
For the race above, safe.sh uses mkdir and flock.sh uses flock. The flock form is preferable: the kernel releases it if the process is killed, while a leftover lock directory has to be cleaned up by hand.
5. Prove the fix
An intermittent failure needs repetition. If the old script failed in about 5% of runs, the chance that it passes any one run is 95%, and the chance it passes n runs in a row by luck is 0.95 to the power n. To be 95% sure a 5%-per-run failure is gone you need the luck probability under 5%: 0.95^58 = 0.051 and 0.95^59 = 0.0485, so 59 consecutive clean runs. Run the stress loop under the same load that failed in production, assert the invariant (exactly one instance did the job) rather than just the exit status, and keep the loop as a regression test.
Pitfalls
- Do not "fix" it by adding
sleep: that narrows the window, it does not remove it, and the problem comes back at the next load increase. set -xitself changes timing, so a race that disappears under tracing is still a race; usestraceor timestamps.- Check whether the failure is in the script at all: a script that fails only under load may be the victim of a slow dependency (a DNS lookup, a network file system mount) rather than the cause.
What is the difference between a shell variable and an environment variable? Explain why VAR=1 bash -c 'echo $VAR' prints nothing, how to make a value visible to child processes, and how you would set one for a single command versus every login session.
Sample Answer
Direct answer
A shell variable lives only inside the shell process that set it. An environment variable is a variable the shell has marked for export, so it is copied into the block of NAME=value strings handed to every program the shell starts. One correction to the question first: VAR=1 bash -c 'echo $VAR' does print 1. A prefix assignment on a command line puts the variable into that command's environment, and the single quotes make the child shell, not the parent, expand $VAR. The commands that print nothing are VAR=1 on its own line followed by bash -c 'echo $VAR', and VAR=1 echo $VAR, which are explained below.
What each case does
unset VAR
echo '1) VAR=1 bash -c '"'"'echo $VAR'"'"
VAR=1 bash -c 'echo "child sees: [$VAR]"'
echo '2) VAR=1 on its own line, then the child'
VAR=1
bash -c 'echo "child sees: [$VAR]"'
echo "parent sees: [$VAR]"
echo '3) VAR=1 echo $VAR (the parent expands $VAR before the assignment applies)'
unset VAR
VAR=1 echo "echo printed: [$VAR]"
echo '4) export, then child changes its copy'
export VAR=1
bash -c 'echo "child sees: [$VAR]"; VAR=99; echo "child now: [$VAR]"'
echo "parent still: [$VAR]"
echo '5) is it exported?'
declare -p VAR
env | grep '^VAR='
echo '6) env VAR=2 for one command, env -u to remove it'
env VAR=2 bash -c 'echo "child sees: [$VAR]"'
env -u VAR bash -c 'echo "child sees: [${VAR-unset}]"'
echo '7) login shell reads ~/.profile'
export HOME=$PWD/fakehome; mkdir -p "$HOME"
echo 'export EDITOR=vim' > "$HOME/.profile"
unset EDITOR
bash -c 'echo "non-login: [${EDITOR-unset}]"'
bash -lc 'echo "login: [${EDITOR-unset}]"'
Output:
1) VAR=1 bash -c 'echo $VAR'
child sees: [1]
2) VAR=1 on its own line, then the child
child sees: []
parent sees: [1]
3) VAR=1 echo $VAR (the parent expands $VAR before the assignment applies)
echo printed: []
4) export, then child changes its copy
child sees: [1]
child now: [99]
parent still: [1]
5) is it exported?
declare -x VAR="1"
VAR=1
6) env VAR=2 for one command, env -u to remove it
child sees: [2]
child sees: [unset]
7) login shell reads ~/.profile
non-login: [unset]
login: [vim]
- Prefix assignment.
VAR=1 bash -c ...exportsVARto that one child. The child sees1. - Plain assignment.
VAR=1on its own line creates a shell variable that is not exported. The child gets no copy, so it prints an empty value, while the parent still has1. This is the case that prints nothing. - Prefix assignment with
echo $VAR. The parent shell expands$VARbefore the assignment takes effect for the command, and it was unset, soechoreceives an empty argument. Expansion happens in the parent, not in the command it launches. export. Afterexport VAR=1the child sees1. The child changed its own copy to 99, and the parent still holds 1: the environment is copied downward atexecve(the system call that starts a program) and never flows back up.- Checking.
declare -p VARshows the-xflag (exported), andenvlists only exported variables. - One command, no shell syntax.
env VAR=2 cmdsets a variable forcmd, andenv -u VAR cmdremoves one. These work with any command and in any shell.
Reading the demo
- Login versus non-login shell. A login shell is the first shell of a session, started when you log in (a console or
sshlogin,su -, orbash -l). Bash marks it as a login shell and reads the profile files (/etc/profile, then~/.profileand friends). A non-login interactive shell is one you open after you are already logged in (a new terminal tab, or typingbash); it reads~/.bashrc. A non-interactive shell (bash script.sh,bash -c '...') reads neither. Bash can tell you which one you are in:bash -c 'shopt login_shell'prints a line withlogin_shellandoff, andbash -lc 'shopt login_shell'prints the same line ending inon(executed;shoptpads the two columns with whitespace). - The quoting in test 1.
echo '1) VAR=1 bash -c '"'"'echo $VAR'"'"glues four pieces together: the single-quoted text1) VAR=1 bash -c, a single quote written as"'", the single-quoted textecho $VAR, and another"'". It is only a way to print a label that itself contains single quotes (1) VAR=1 bash -c 'echo $VAR'). The real test is the line after it. - The
HOMEtrick in test 7. Bash finds~/.profilethrough theHOMEvariable. PointingHOMEat a scratch directory (fakehome) lets the demo create a.profilewithout touching the real one. execve. The Linux system call that replaces a process with a new program and hands it its arguments and its environment. Exported variables are copied into that environment at this moment, which is why later changes never flow back.declare -p VAR. Prints how Bash holds the variable;declare -x VAR="1"has the-xflag, meaning exported./proc/PID/environ. Linux shows each running process as a folder under/proc; the fileenvironholds the environment the process started with, separated by NUL bytes. Executed:VAR=1 sleep 5 &thentr '\0' '\n' < /proc/$!/environ | grep '^VAR='printsVAR=1.env_reset. A setting ofsudo(on by default) that starts the command with a cleaned-up environment instead of yours.
Making a value visible to children
Use export VAR=value, or VAR=value; export VAR for older POSIX shells. In Bash, declare -x does the same. Exporting is a one-way flag for that shell and its descendants. It does not affect sibling shells or the parent, and it does not survive logout.
One command versus every login session
Choose by who starts the process; the list is not a sequence to work through. For your own interactive sessions, one export line in ~/.profile is the usual answer. The other entries cover other starters.
- One command:
VAR=value commandorenv VAR=value command. Nothing remains afterwards. - Every login session of one user: put
export VAR=valuein~/.profile. Bash login shells read/etc/profileand then the first of~/.bash_profile,~/.bash_login,~/.profilethat exists. Test 7 above shows the effect: a plainbash -cdid not seeEDITOR, andbash -lc(a login shell) did. Interactive non-login shells, such as a new terminal tab on many desktops, read~/.bashrcinstead, so people often source~/.bashrcfrom the profile or the reverse. - Every user:
/etc/profile.d/*.shfor login shells, or/etc/environmenton Debian and Ubuntu, which is read by the PAM modulepam_env(Pluggable Authentication Modules) and takes plainNAME=valuelines with no shell syntax. - Services and cron jobs: they do not read profile files. For a systemd unit use
Environment=orEnvironmentFile=. A cron job starts with a minimal environment, so set what it needs in the crontab or script.
Pitfalls
- Environment variables are readable by the same user and by root through
/proc/PID/environ, and are inherited by every child, so a secret exported in a login profile is handed to every program that user starts. Prefer passing secrets to the one command that needs them. sudoresets most variables by default (itsenv_resetsetting), so an exported variable can disappear acrosssudounless the policy keeps it.- Variables set inside a
( subshell ), a pipeline stage or a$(...)do not return to the parent.
Write a backup script that takes incremental snapshots of a data directory, keeps daily, weekly and monthly generations, verifies each backup and cleans up on failure. What would make you distrust its first successful run?
Sample Answer
Direct answer
Use rsync with --link-dest to build each daily snapshot as a full-looking directory tree in which unchanged files are hard links to yesterday's copy, so only changed files consume space. Build the snapshot in a staging directory, verify it with a checksum comparison against the source, and publish it with one atomic rename only if verification passes; a trap removes the staging directory on any failure. Promote the daily snapshot to weekly (Sundays) and monthly (the 1st) with hard-link copies, then prune each tier to its retention count (7 daily, 4 weekly, 6 monthly). The first successful run deserves distrust because it is a full copy: the incremental path, the retention path and, above all, the restore path have not been exercised yet.
The script
#!/usr/bin/env bash
# snapshot-backup.sh SRC DEST
# Hard-linked incremental snapshots (rsync --link-dest) with daily, weekly and monthly generations.
# DEST/daily/YYYY-MM-DD kept: 7 (every run)
# DEST/weekly/YYYY-MM-DD kept: 4 (promoted on Sundays)
# DEST/monthly/YYYY-MM-DD kept: 6 (promoted on the 1st)
set -euo pipefail
src=${1:?usage: snapshot-backup.sh SRC DEST}; dest=${2:?usage: snapshot-backup.sh SRC DEST}
today=${TODAY:-$(date +%F)} # TODAY is only overridden by tests
keep_daily=7 keep_weekly=4 keep_monthly=6
min_files=${MIN_FILES:-1} # refuse to snapshot a source that looks empty
stage=$dest/.inprogress
[[ -d $src ]] || { echo "source $src is missing" >&2; exit 2; }
mkdir -p -- "$dest"/{daily,weekly,monthly}
exec 9>"$dest/.lock"; flock -n 9 || { echo "another backup is running" >&2; exit 0; }
cleanup() { local rc=$?; if (( rc != 0 )); then rm -rf -- "$stage"; echo "FAILED (status $rc), partial snapshot removed" >&2; fi; }
trap cleanup EXIT
if [[ -e $dest/daily/$today ]]; then echo "snapshot $today already exists"; exit 0; fi
# 1. Sanity: an unmounted or emptied source must not become a "successful" backup.
files=$(find "$src" -type f | wc -l)
(( files >= min_files )) || { echo "source has $files files, expected at least $min_files" >&2; exit 3; }
# 2. Copy into a staging directory, hard-linking unchanged files to the previous snapshot.
rm -rf -- "$stage"
prev=$(find "$dest/daily" -mindepth 1 -maxdepth 1 -type d | sort | tail -n 1)
link=(); [[ -n $prev ]] && link=(--link-dest="$prev")
rsync -aH --numeric-ids --delete "${link[@]}" -- "$src"/ "$stage"/
# 3. Verify: a checksum comparison against the source must list zero differences.
diff_out=$(rsync -aH --numeric-ids --checksum --dry-run --itemize-changes --delete -- "$src"/ "$stage"/)
if [[ -n $diff_out ]]; then echo "verification found differences:" >&2; echo "$diff_out" >&2; exit 4; fi
# 4. Publish atomically: the name appears only after verification passed.
mv -- "$stage" "$dest/daily/$today"
echo "snapshot $today: $files files, verified"
# 5. Promote with hard links (no extra space), then prune each tier.
(( $(date -d "$today" +%u) == 7 )) && cp -al -- "$dest/daily/$today" "$dest/weekly/$today"
[[ $(date -d "$today" +%d) == 01 ]] && cp -al -- "$dest/daily/$today" "$dest/monthly/$today"
prune() {
local dir=${1:?} n=$2 d
while IFS= read -r d; do
rm -rf -- "${dir:?}/$d"; echo "pruned ${dir##*/}/$d"
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | sort -r | tail -n +"$(( n + 1 ))")
}
prune "$dest/daily" "$keep_daily"; prune "$dest/weekly" "$keep_weekly"; prune "$dest/monthly" "$keep_monthly"
Reading the script
The rsync flags. Each flag below is in the rsync manual.
-a(archive) is shorthand for-rlptgoD: recurse into directories, copy symlinks as symlinks, and preserve permissions, modification times, group, owner and device files. It does not include-H.-Hpreserves hard links that exist inside the source tree.--numeric-idskeeps the owner and group as raw numbers instead of translating them through user and group names, which is what a backup wants when the restore happens on a different machine.--deleteremoves files from the destination that no longer exist in the source, so the copy mirrors the source exactly.--link-dest=DIRis the heart of the design: when a file is unchanged compared with the same path underDIR(the previous snapshot), rsync makes a hard link to it instead of copying the data. A hard link is a second directory entry for the same file data, so it costs almost no space.--checksummakes rsync compare files by a content checksum instead of by size and modification time.--dry-run(-n) reports what it would do without doing it.--itemize-changes(-i) prints one coded line for every difference found, so a dry run with--checksumand--itemize-changesprints nothing when source and copy are identical.- The trailing
/in"$src"/means "the contents of the directory", and--marks the end of the options.
link=(); [[ -n $prev ]] && link=(--link-dest="$prev") and "${link[@]}". link is an array. It stays empty on the very first run (no previous snapshot) and otherwise holds the single word --link-dest=<previous snapshot>. "${link[@]}" expands to each element as its own word, so an empty array vanishes from the command line and a path containing spaces stays one word. Tested in the container: with prev empty, show a "${link[@]}" b received 2 words; with prev=/bk/daily/2026-10-04 it received 3, the middle one --link-dest=/bk/daily/2026-10-04, and a prev of /my backups/2026-10-04 still gave 3 words.
trap cleanup EXIT and local rc=$?. A trap runs a command when an event happens; EXIT fires whenever the script ends, success or failure. $? is the exit status of the last command, so cleanup copies it into rc on its first line, before any other command can change it. A script that does exit 4 made the trap report trap saw status 4, and a script that simply finished made it report 0. Only a non-zero status triggers the removal of .inprogress.
(( $(date -d "$today" +%u) == 7 )) && cp -al .... date -d "$today" +%u prints the weekday number, 1 for Monday to 7 for Sunday (checked: 2026-10-04 gives 7 and 2026-10-05 gives 1). (( ... == 7 )) is an arithmetic test that succeeds only for 7, and && runs the cp only when the test succeeded. In cp -al, -a copies everything with its attributes and -l makes hard links instead of copying data. The monthly line does the same with date +%d, the day of the month, compared with 01.
How it behaves
- Incremental by hard links. A snapshot directory looks complete, but a file that did not change is the same inode (the filesystem's single record of that file's data) as in the previous snapshot. Deleting an old snapshot only frees the files no newer snapshot still links to.
- Atomic publish. Work happens in
.inprogress. The dated name appears only after verification, so a snapshot that exists indaily/is a verified one. The base for--link-destis chosen fromdaily/only, so a failed run can never become the base of the next one. - Verification. The second
rsyncis a dry run with--checksum: it reads both sides in full and lists every difference. Any output fails the backup (exit 4). For a live data directory the comparison can race with writers, so pointSRCat a filesystem snapshot (LVM, btrfs, ZFS) when the data changes while the backup runs. - Cleanup on failure. The
EXITtrap deletes.inprogresswhenever the exit status is non-zero. Earlier snapshots are never modified. - Idempotence and concurrency. A non-blocking
flockprevents overlapping runs, and a snapshot that already exists for today is not redone. - Guard against an empty source. An unmounted or emptied source would otherwise produce a "successful" backup of nothing, and the verification step would pass, because an empty staging copy matches an empty source.
MIN_FILESmakes that a failure (exit 3). - Weekly and monthly generations.
date +%uis 7 on Sunday (ISO numbering, Monday is 1).cp -alcreates the promoted copy with hard links, so a weekly or monthly generation costs directory entries, not data. If a Sunday run is missed there is no weekly for that week; promoting the first successful run of each ISO week removes that gap.
Test run
The simulation runs one backup per day from 2026-08-01 to 2026-10-05 (66 days), with TODAY overriding the date, one 1 MiB file that never changes and a notes file that changes every day (with a new modification time each day). Then it checks retention against an independent calculation, inspects hard links, repeats a day that already has a snapshot, and injects two failures (an empty source and an unreadable file).
run.sh:
cd /w
shellcheck -s bash snapshot-backup.sh && echo "shellcheck clean"
mkdir -p /data/docs /bk; head -c 1048576 /dev/urandom > /data/big.bin; echo v0 > /data/docs/notes.txt
echo "== simulate 2026-08-01 .. 2026-10-05, one run per day, notes.txt changes daily"
for off in $(seq 0 65); do
d=$(date -d "2026-08-01 +$off day" +%F)
echo "$d" > /data/docs/notes.txt; touch -d "$d 12:00" /data/docs/notes.txt
TODAY=$d bash snapshot-backup.sh /data /bk > /dev/null
done
echo "== daily"; ls /bk/daily | tr '\n' ' '; echo
echo "== weekly"; ls /bk/weekly | tr '\n' ' '; echo
echo "== monthly"; ls /bk/monthly | tr '\n' ' '; echo
echo "== expected weekly (last 4 Sundays) and monthly (1st of month)"
python3 - <<'P'
import datetime as dt
days=[dt.date(2026,8,1)+dt.timedelta(n) for n in range(66)]
print("weekly :", " ".join([str(d) for d in days if d.isoweekday()==7][-4:]))
print("monthly:", " ".join([str(d) for d in days if d.day==1][-6:]))
P
echo "== hard links: unchanged file shares one inode across snapshots, changed file does not"
stat -c '%h links inode %i %n' /bk/daily/2026-10-05/big.bin /bk/daily/2026-10-05/docs/notes.txt /bk/daily/2026-10-04/docs/notes.txt
echo "== disk use of all snapshots (KiB) vs one snapshot"
du -sk /bk | cut -f1; du -sk /bk/daily/2026-10-05 | cut -f1
echo "== same day twice"; TODAY=2026-10-05 bash snapshot-backup.sh /data /bk
echo "== empty source is refused"; mkdir /empty; TODAY=2026-10-06 bash snapshot-backup.sh /empty /bk; echo "exit: $?"; ls -A /bk | tr '\n' ' '; echo
echo "== unreadable file, run as an unprivileged user"
mkdir -p /bk2 && chown 1000:1000 /bk2; echo secret > /data/docs/root-only.txt; chmod 000 /data/docs/root-only.txt
chmod 755 /w
setpriv --reuid=1000 --regid=1000 --clear-groups env TODAY=2026-10-06 bash snapshot-backup.sh /data /bk2; echo "exit: $?"
ls -A /bk2 /bk2/daily | tr '\n' ' '; echo
Run in an Ubuntu 24.04 container with rsync 3.2.7:
shellcheck clean
== simulate 2026-08-01 .. 2026-10-05, one run per day, notes.txt changes daily
== daily
2026-09-29 2026-09-30 2026-10-01 2026-10-02 2026-10-03 2026-10-04 2026-10-05
== weekly
2026-09-13 2026-09-20 2026-09-27 2026-10-04
== monthly
2026-08-01 2026-09-01 2026-10-01
== expected weekly (last 4 Sundays) and monthly (1st of month)
weekly : 2026-09-13 2026-09-20 2026-09-27 2026-10-04
monthly: 2026-08-01 2026-09-01 2026-10-01
== hard links: unchanged file shares one inode across snapshots, changed file does not
14 links inode 2418380 /bk/daily/2026-10-05/big.bin
1 links inode 2418863 /bk/daily/2026-10-05/docs/notes.txt
2 links inode 2418857 /bk/daily/2026-10-04/docs/notes.txt
== disk use of all snapshots (KiB) vs one snapshot
1072
1028
== same day twice
snapshot 2026-10-05 already exists
== empty source is refused
source has 0 files, expected at least 1
FAILED (status 3), partial snapshot removed
exit: 3
.lock daily monthly weekly
== unreadable file, run as an unprivileged user
rsync: [sender] send_files failed to open "/data/docs/root-only.txt": Permission denied (13)
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1356) [sender=3.2.7]
FAILED (status 23), partial snapshot removed
exit: 23
/bk2: .lock daily monthly weekly /bk2/daily:
Reading the result: the seven newest days remain in daily, the last four Sundays in weekly, and the 1st of each of the three months in monthly (the tier would keep six, but only three exist in a 66-day run); the Python lines compute the same weekly and monthly sets independently. The unchanged 1 MiB file has 14 links, which is 7 daily plus 4 weekly plus 3 monthly directory entries pointing at one inode, while the daily notes file has one link and its Sunday copy two. Everything retained (7 daily, 4 weekly and 3 monthly directories) occupies 1072 KiB in total, against 1028 KiB for one snapshot on its own. The failure cases left no staging directory and no new snapshot: an empty source exited 3, and an unreadable file (running as an unprivileged user) exited 23, which is rsync's "some files were not transferred".
The tally behind those numbers (measured in a repeat of the same 66-day run: 1072 KiB in total, 1028 KiB for one snapshot). The unchanged big.bin has one inode, referenced from 7 daily + 4 weekly + 3 monthly directories, so 14 entries and 14 links, but its 1024 KiB is stored once. notes.txt changes every day, so every daily snapshot has its own inode, 7 in all. A weekly snapshot was made by cp -al from the daily one of that day, so it shares that inode while the daily copy exists: the weekly snapshots of 09-13, 09-20 and 09-27 are no longer in daily/ and hold 3 more inodes, while the one for 10-04 shares an inode with a daily snapshot. In the same way, the monthly snapshots of 08-01 and 09-01 hold 2 more inodes, and the one for 10-01 shares one. That gives 7 + 3 + 2 = 12 distinct notes.txt inodes (find /bk -name notes.txt -printf '%i\n' | sort -u | wc -l printed 12 and find /bk -name notes.txt | wc -l printed 14). Each holds an 11-byte file, which the filesystem stores in one 4 KiB block. So the total is 1024 + 12 x 4 = 1072 KiB, and one snapshot alone is 1024 + 4 = 1028 KiB; the 44 KiB difference is the 11 extra notes.txt blocks. Directories counted as 0 KiB on this filesystem (overlayfs), and other filesystems charge for them, so expect a larger total elsewhere.
A restore check on a fresh, tiny dataset (this is what a restore drill looks like):
mkdir -p /data/docs /bk; head -c 100000 /dev/urandom > /data/big.bin; echo hello > /data/docs/a.txt
bash snapshot-backup.sh /data /bk
mkdir /restore; rsync -a /bk/daily/*/ /restore/
diff -r /data /restore && echo "restore identical"
snapshot 2026-10-06: 2 files, verified
restore identical
What would make me distrust the first successful run
- It was a full copy, so the incremental logic has not run. Check the second run: it should add almost no space and show hard-link counts above 1 on unchanged files (as above). A destination that cannot hard-link would give you a full copy per snapshot, and the link counts are where you would see it. Executed on an 8 MiB FAT-formatted loop image mounted with
mount -o loop:rsync -a --link-destexited 0 and quietly copied the data again (both snapshot files showed 1 link), whilecp -alfailed withcp: cannot create hard link '/fat/weekly1/d/f' to '/fat/daily/1/d/f': Operation not permitted(status 1), so a destination that cannot hard-link both wastes space and breaks the weekly and monthly promotion. - rsync decides "unchanged" from size and modification time. If a file is rewritten with the same size and the same timestamp, rsync links the old content into the new snapshot and nothing looks wrong. The checksum verification is what catches it. This reproduces it:
mkdir -p /data /bk; printf 'AAAAA' > /data/notes.txt; touch -d '2026-10-01 12:00:00' /data/notes.txt
TODAY=2026-10-01 bash snapshot-backup.sh /data /bk
printf 'BBBBB' > /data/notes.txt; touch -d '2026-10-01 12:00:00' /data/notes.txt # same size, same mtime
TODAY=2026-10-02 bash snapshot-backup.sh /data /bk; echo "exit: $?"
ls /bk/daily
snapshot 2026-10-01: 1 files, verified
verification found differences:
>fc........ notes.txt
FAILED (status 4), partial snapshot removed
exit: 4
2026-10-01
In that line >fc........ notes.txt, the first character > says the file would be received into the destination (it would be transferred). f says the item is a regular file. c says its checksum differs, which is possible only because of --checksum. Each . stands for an attribute that is unchanged: size, modification time, permissions, owner, group and so on. rsync's own first pass saw the same size and time and skipped the file; only the checksum run noticed the difference.
- It has never been restored. A backup that has not been restored and compared is a hypothesis. Schedule a restore drill into a scratch directory and compare, including permissions and a database dump if the directory holds a live database (copying database files while it runs gives an inconsistent backup).
- The source may have been wrong. An empty mount, a path typo, exclusions that skip data, or files the backup user cannot read (exit 23) all produce plausible-looking success. Compare file counts and sizes against what you expect.
- Metadata and scope. Run as root to keep ownership; add
-A -Xfor access control lists (ACLs) and extended attributes if the system uses them (the destination and rsync build must support them). - The failure path is untested until you break it. Cause each failure on purpose, as above, and confirm an alert fires: a backup that fails silently is the real danger.
- Same host, same failure domain. Snapshots on the machine they protect do not survive its loss; copy them offsite.
How do arrays work in Bash, and where does POSIX sh differ? Write a script that stores a list of filenames given as arguments (some containing spaces) and prints each as 'index: name'.
Sample Answer
Direct answer
A Bash array is an ordered list of separate strings, indexed from 0. Word splitting is the shell cutting an unquoted expansion into separate words at spaces, tabs and newlines (the default characters of IFS, the Internal Field Separator), and a glob is a wildcard pattern (*, ?, [...]) that the shell replaces with matching file names; double quotes switch both off for the expansion they wrap. You create one with files=("$@"), count it with ${#files[@]}, and loop over its indices with ${!files[@]}. Each element is its own string, so spaces inside a filename are harmless as long as every expansion is quoted. POSIX sh (the Portable Operating System Interface shell standard, which dash and BusyBox ash follow) has no arrays at all. Its only list is the positional parameters $1 $2 ..., reachable as "$@".
The Bash script
#!/usr/bin/env bash
# list.sh: print each argument as "index: name" (bash arrays)
files=("$@") # copy the arguments into an array, one element each
printf 'count=%d\n' "${#files[@]}"
for i in "${!files[@]}"; do # "${!files[@]}" expands to the indices 0 1 2 ...
printf '%d: %s\n' "$i" "${files[$i]}"
done
files+=("added later.txt") # append one element
printf 'last=%s\n' "${files[-1]}" # negative index needs bash 4.3+
printf 'slice=[%s]\n' "${files[@]:1:2}"
Choices that matter:
files=("$@")copies the arguments with their boundaries intact."$@"expands to one word per argument, and the quotes stop the shell from splittingmy report.txtinto two words."${!files[@]}"expands to the list of indices. Arrays can be sparse (afterunset 'files[1]'the indices are 0 and 2), so counting from 0 to${#files[@]}is wrong, while looping over the real indices is always right."${files[$i]}"is quoted for the same reason as any other expansion.printf '%d: %s\n'is used instead ofechobecause a filename that starts with-or contains backslashes can be misread byecho.${files[@]:1:2}is a slice: two elements starting at index 1, so with the demo's arguments plus the appended element (my report.txt,two spaces.log,plain.txt,added later.txt) it yieldstwo spaces.logandplain.txt.printfreuses its format string once per extra argument, which is why the slice line prints twice.files+=("added later.txt")appends one element;set -- "$@" "new item"in POSIX sh does the same for the positional parameters (set --replaces them with the words that follow).
The same job in POSIX sh
#!/bin/sh
# list-posix.sh: POSIX sh version, no arrays: the positional parameters are the list
i=0
for f in "$@"; do
printf '%d: %s\n' "$i" "$f"
i=$((i + 1))
done
With no arrays, the loop walks "$@" and keeps its own counter. Arithmetic expansion $((i + 1)) is POSIX, so this runs under any conforming shell. To keep a second list in POSIX sh you rebuild the positional parameters with set -- "$@" "new item", which is the only append available.
Running both
$ bash list.sh "my report.txt" "two spaces.log" plain.txt
count=3
0: my report.txt
1: two spaces.log
2: plain.txt
last=added later.txt
slice=[two spaces.log]
slice=[plain.txt]
$ dash list-posix.sh "my report.txt" "two spaces.log" plain.txt
0: my report.txt
1: two spaces.log
2: plain.txt
$ bash -c 'files=($*); echo "${#files[@]} elements"' _ "my report.txt" "two spaces.log" plain.txt
5 elements
$ dash -c 'a=(x y); echo ${a[1]}'
dash: 1: Syntax error: "(" unexpected
$ bash --posix -c 'a=(x y); echo ${a[1]}'
y
In the bash -c '...' _ args line, -c takes the commands from the quoted string, and the words after the string become that command's $0, $1, $2, ...; _ is a throwaway placeholder that fills $0 (the program name slot) so the three file names land in $1, $2, $3. Run alone, bash -c 'echo "0=[$0] 1=[$1]"' _ first second prints 0=[_] 1=[first]. Unquoted $* pastes the three arguments into one string, which the shell then splits at the spaces (my, report.txt, two, spaces.log ...) and checks for glob characters, which is where the five elements come from.
The $* line shows the failure to avoid: an unquoted expansion is split on whitespace and then expanded as a glob pattern, so three arguments became five elements. The last two commands show where the portability line sits. dash rejects array syntax with a syntax error, while bash --posix still accepts arrays, so running a script under bash --posix is not a portability test. Test with dash, or with #!/bin/sh on a Debian or Ubuntu host where /bin/sh is dash.
Where the dialects differ
The two versions that matter most in practice are Bash 3.2 (the /bin/bash on macOS) and any Bash 4.4 or later (current Linux distributions); the middle versions only matter if you must support a specific older server.
| Feature | Bash 4.4+ | POSIX sh (dash) |
|---|---|---|
Indexed array a=(x y) | yes, 0-based | syntax error |
Associative array declare -A m | yes (Bash 4+) | no |
Negative index ${a[-1]} | yes (Bash 4.3+) | no |
${!a[@]}, ${#a[@]}, += append | yes | no |
Positional parameters "$@", set -- | yes | yes (the only list) |
macOS ships Bash 3.2, which predates associative arrays and negative indexes, so a script that uses them fails under /bin/bash on a Mac even though it runs on a current Linux host. zsh arrays start at index 1 by default, which is another reason not to assume a[0] works everywhere.
Pitfalls
- Under
set -u, expanding an empty array as"${files[@]}"is an "unbound variable" error before Bash 4.4. This script has noset -u, but one added later would break the no-arguments case on older Bash. "${files[*]}"joins the elements into one string using the first character ofIFS(the Internal Field Separator, a variable that controls how the shell splits words). It is for display, not for passing a list on.- Filling an array from command output needs care:
files=($(ls))splits on spaces and expands globs.mapfile -t files < <(command)reads the output ofcommandinto the array, one line per element:mapfile(also calledreadarray) is a Bash built-in,-tstrips each trailing newline, and<(command)is process substitution, which runscommandand hands the shell a file name to read its output from, so< <(command)redirects that output intomapfile(Bash 4+). For examplemapfile -t lines < <(printf 'x y\nz\n')gives two elements,x yandz. Usemapfile -d '' -t files < <(find ... -print0)when names may contain newlines. Plainmapfile -tworks from Bash 4.0, but the-doption needs Bash 4.4 or later: Bash 4.3 answersmapfile: -d: invalid option(checked), and Bash 3.2 has nomapfileat all. - A sparse array has gaps in its indices. After
files=(a "b c" d e)andunset 'files[1]',${!files[@]}prints0 2 3and${#files[@]}is 3, so the highest index is not the count minus one.
Unlock Full Question Bank
Get access to all 47 Shell Scripting and Automation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.