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.
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.
A script with #!/bin/sh works on your laptop but fails inside an Alpine container. What Bash-specific features probably crept in, how do you find them, and how do you decide between rewriting for POSIX sh and just requiring Bash?
Sample Answer
Direct answer
On Alpine, /bin/sh is the ash shell from BusyBox (one small program that bundles minimal versions of the standard utilities), not Bash. It follows POSIX (the standard that defines portable shell behaviour) plus some extras. A script that begins #!/bin/sh but uses Bash-only syntax (arrays, ${var^^}, here-strings <<<, (( )), brace ranges like {1..3}) fails there, or worse, silently behaves differently. Find them by running the script with the target sh in continuous integration (CI) and by running ShellCheck in sh mode. Then decide: rewrite to POSIX when the script is short glue that has to run in minimal images; require Bash (change the shebang to #!/usr/bin/env bash and install it) when the logic really needs arrays or Bash features.
Why it works on the laptop
The laptop's /bin/sh is usually more permissive. On macOS and on Red Hat style systems /bin/sh is Bash itself (I checked an AlmaLinux 9 image: /bin/sh is bash, and the constructs I probed matched Bash), and Bash in sh mode still accepts most Bash syntax. Debian and Ubuntu use dash (the Debian Almquist shell, a small, fast POSIX shell), which is stricter. Alpine uses BusyBox ash (BusyBox's version of the same Almquist shell), whose feature set depends on how that BusyBox was built.
What crept in
This script has the usual suspects:
#!/bin/sh
set -eu
hosts=(web1 web2 db1)
env_name=${1:-prod}
if [[ $env_name == prod* ]]; then
echo "production run"
fi
for h in "${hosts[@]}"; do
echo "checking $h"
done
echo "${env_name^^} done"
count=$(( ${#hosts[@]} * 2 ))
echo "total checks: $count"
echo -e "tab:\tseparated"
set -eu makes the script stop at the first failing command (-e) and treat any use of an unset variable as an error (-u); both are POSIX.
$ sh deploy-check.sh
deploy-check.sh: line 3: syntax error: unexpected "("
exit=2
BusyBox stops at the first syntax error (the array on line 3), so one message can hide other problems. ShellCheck in sh mode reports the Bash-only constructs it recognises (the SC3xxx codes are its "not defined in POSIX sh" family):
$ shellcheck -s sh -f gcc deploy-check.sh
deploy-check.sh:3:7: warning: In POSIX sh, arrays are undefined. [SC3030]
deploy-check.sh:5:4: warning: In POSIX sh, [[ ]] is undefined. [SC3010]
deploy-check.sh:5:17: warning: In POSIX sh, == in place of = is undefined. [SC3014]
deploy-check.sh:8:11: warning: In POSIX sh, array references are undefined. [SC3054]
deploy-check.sh:11:7: warning: In POSIX sh, case modification is undefined. [SC3059]
deploy-check.sh:14:6: warning: In POSIX sh, echo flags are undefined. [SC3037]
$ shellcheck -s sh deploy-check-posix.sh; echo "exit=$?"
exit=0
Each line reads file:line:column: severity: message [code]. The report has six entries, but line 12, count=$(( ${#hosts[@]} * 2 )), also uses array syntax and ShellCheck does not list it here (checked by running it alone: it reports only an unused variable and an unassigned hosts). A linter is a net with holes, so a clean run does not prove the script is POSIX: run the script itself under the target shell as well.
Measure, do not assume: constructs against three shells
probe.sh runs one snippet per construct under a named shell and compares the output with what Bash prints. The constructs, in plain words:
a=(x y)is an array, a variable holding a numbered list;[[ ]]is Bash's extended test (pattern matching);(( ))is an arithmetic command;{1..3}is brace expansion (the shell writes out1 2 3).echo -emakesechointerpret backslash escapes such as\t;${v^^}upper-cases a value;${v//a/X}replaces everyawithX;${v:1:2}takes two characters starting at offset 1.<<<(here-string) feeds a string to a command's standard input;<(cmd)(process substitution) presents a command's output as if it were a file;source fileruns a file's commands in the current shell (POSIX spells it.).function f { ...; }is the Bash keyword form of defining a function;localmakes a variable private to a function;set -o pipefailmakes a pipeline fail if any stage fails, not only the last;$'a\tb'is ANSI-C quoting, which turns\tinto a real tab.
How the helper works: probe label want snippet runs $sh_bin -c "$snippet" (-c means "take the commands from this string"), merges error messages into the output with 2>&1, keeps only the first line with head -n 1, and captures it with $(...). If that equals want (what Bash prints) the verdict is same, otherwise DIFFERENT; printf '%-18s %-9s %s\n' pads the three columns. tab=$(printf '\t') stores a tab character so tab results can be compared.
The last probe line looks odd because the snippet contains single quotes. A single quote cannot appear inside a single-quoted string, so the line splices four pieces together: 'printf "%s\n" $', then "'" (a quote character in double quotes), then 'a\tb', then "'" again. The snippet that reaches the shell is printf "%s\n" $'a\tb'.
# usage: probe.sh SHELL ; prints what each construct does under SHELL and whether it matches bash
sh_bin=$1
tab=$(printf '\t')
probe() {
label=$1; want=$2; snippet=$3
got=$($sh_bin -c "$snippet" 2>&1 | head -n 1)
if [ "$got" = "$want" ]; then verdict=same; else verdict=DIFFERENT; fi
printf '%-18s %-9s %s\n' "$label" "$verdict" "$got"
}
probe 'array' 'y' 'a=(x y); echo ${a[1]}'
probe '[[ ]]' 'match' '[[ abc == a* ]] && echo match'
probe '(( ))' '2' 'i=1; ((i++)); echo $i'
probe 'brace expansion' '1 2 3' 'echo {1..3}'
probe 'echo -e' "a${tab}b" 'echo -e "a\tb"'
probe '${v^^}' 'ABC' 'v=abc; echo ${v^^}'
probe '${v//a/X}' 'bXnXnX' 'v=banana; echo ${v//a/X}'
probe '${v:1:2}' 'el' 'v=hello; echo ${v:1:2}'
probe 'here-string' 'hi' 'cat <<< hi'
probe 'process subst' 'hi' 'cat <(echo hi)'
probe 'source' '1' 'echo x=1 > /tmp/s.sh; source /tmp/s.sh; echo $x'
probe 'function keyword' 'hi' 'function f { echo hi; }; f'
probe 'local' '1' 'f() { local x=1; echo $x; }; f'
probe 'pipefail' '1' 'set -o pipefail; false | true; echo $?'
probe 'dollar-quote' "a${tab}b" 'printf "%s\n" $'"'"'a\tb'"'"
The reference run under Bash matches every expectation. In the two tables after it, DIFFERENT followed by an error message means the construct failed outright. DIFFERENT with no error (brace expansion on both shells, and echo -e and $'...' on dash) means the shell ran the command and printed something else, which is the dangerous case because nothing stops the script. same means the construct works in that shell.
$ sh probe.sh bash # reference
array same y
[[ ]] same match
(( )) same 2
brace expansion same 1 2 3
echo -e same a b
${v^^} same ABC
${v//a/X} same bXnXnX
${v:1:2} same el
here-string same hi
process subst same hi
source same 1
function keyword same hi
local same 1
pipefail same 1
dollar-quote same a b
Alpine 3 (BusyBox v1.37.0 here):
$ busybox | head -n 1 # the version banner; probe.sh itself does not print it
BusyBox v1.37.0 (2026-01-10 15:38:28 UTC) multi-call binary.
$ sh probe.sh sh # Alpine 3, BusyBox ash
array DIFFERENT sh: syntax error: unexpected "("
[[ ]] same match
(( )) DIFFERENT sh: i++: not found
brace expansion DIFFERENT {1..3}
echo -e same a b
${v^^} DIFFERENT sh: syntax error: bad substitution
${v//a/X} same bXnXnX
${v:1:2} same el
here-string DIFFERENT sh: syntax error: unexpected redirection
process subst same hi
source same 1
function keyword same hi
local same 1
pipefail same 1
dollar-quote same a b
Ubuntu 24.04 (dash):
$ sh probe.sh sh # Ubuntu 24.04, dash
array DIFFERENT sh: 1: Syntax error: "(" unexpected
[[ ]] DIFFERENT sh: 1: [[: not found
(( )) DIFFERENT sh: 1: i++: not found
brace expansion DIFFERENT {1..3}
echo -e DIFFERENT -e a b
${v^^} DIFFERENT sh: 1: Bad substitution
${v//a/X} DIFFERENT sh: 1: Bad substitution
${v:1:2} DIFFERENT sh: 1: Bad substitution
here-string DIFFERENT sh: 1: Syntax error: redirection unexpected
process subst DIFFERENT sh: 1: Syntax error: "(" unexpected
source DIFFERENT sh: 1: source: not found
function keyword DIFFERENT sh: 1: Syntax error: "}" unexpected
local same 1
pipefail DIFFERENT sh: 1: set: Illegal option -o pipefail
dollar-quote DIFFERENT $a\tb
Three lessons from the data. First, BusyBox 1.37 accepted [[ ]], ${v//a/X}, ${v:1:2}, source, pipefail, echo -e, process substitution, the function keyword and local, but rejected arrays, (( )), brace expansion, ${v^^} and here-strings, so "Alpine has no Bash features" is too strong and "it works on Alpine" depends on the BusyBox version. Second, brace expansion and (( )) fail silently or with a confusing message: echo {1..3} prints the literal {1..3}, and ((i++)) prints i++: not found (ash reads ((i++)) as a subshell inside a subshell running a command named i++, so the status is 127). Without set -e the script carries on past it; with set -e it stops there. Both were checked on BusyBox ash. Third, dash rejects most of the list and differs on echo -e (prints -e), so testing on both catches more than either alone.
Finding them systematically
- Run the script under the real target shell in the real image (
docker run --rm -v "$PWD":/w alpine:3 sh /w/script.sh), including every code path. - Run
shellcheck -s sh script.sh; its SC3xxx warnings are exactly the "undefined in POSIX sh" constructs. Debian'scheckbashismsis another tool for this (I did not run it here). - Test under
dashas well, because it is the strictest common/bin/sh. - Note that
bash --posixis not a POSIX checker: it still accepts many extensions.
The POSIX rewrite
#!/bin/sh
set -eu
hosts="web1 web2 db1"
env_name=${1:-prod}
case $env_name in
prod*) echo "production run" ;;
esac
count=0
for h in $hosts; do
echo "checking $h"
count=$((count + 2))
done
echo "$(printf '%s' "$env_name" | tr '[:lower:]' '[:upper:]') done"
echo "total checks: $count"
printf 'tab:\tseparated\n'
$ sh deploy-check-posix.sh prod # Alpine
production run
checking web1
checking web2
checking db1
PROD done
total checks: 6
tab: separated
exit=0
Arrays became a space-separated list (safe here because the words contain no spaces), [[ == prod* ]] became case, ${v^^} became tr, (( )) became $(( )), and echo -e became printf.
Rewrite or require Bash?
Recommendation: rewrite to POSIX if the script is under roughly a screen, has to run in minimal images (FROM alpine, distroless images that hold only the application and its libraries with no shell at all, and init containers, the short setup containers that run before the main one in Kubernetes) and needs only simple lists; require Bash when it needs arrays of values with spaces, associative arrays, [[ ]] regex matching or mapfile, because emulating those in POSIX is where bugs come from. Requiring Bash costs apk add bash (an extra package and a slightly bigger image) plus a shebang that says what you mean. Whichever you pick, make the shebang match the dialect, put shellcheck -s sh or -s bash in CI, and run the script in the target image in CI so a regression fails the build, not the deploy.
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.
You must find the last N ERROR lines across 10,000 compressed log files spread over several servers. Describe a brute-force approach and a faster one with concrete shell commands, and reason about their cost.
Sample Answer
Direct answer
Brute force reads every file on every server: decompress all 10,000 archives, keep every ERROR line, ship them all to one place, sort, and take the last N. The faster way never reads most of that. Rotated logs (a logging system closes the current file at a fixed interval, compresses it to a .log.gz archive and starts a new one) are written in time order, so the newest files hold the newest lines: on each server, walk the files newest first, stop as soon as N matching lines have been found, ship at most N lines per server, and merge those few lines on the machine you run from. The work then scales with N and the error density, not with the archive size. Assume each line starts with an ISO 8601 UTC timestamp (so text order is time order) and that files are rotated by time (so a newer file never contains older lines than an older file).
Brute force
#!/usr/bin/env bash
set -euo pipefail
n=$1
shift
for h in "$@"; do
ssh -o BatchMode=yes "$h" 'find logs -name "*.log.gz" -print0 | xargs -0 zgrep -a -h " ERROR " || [ $? -eq 123 ]' | sed "s/\$/ host=$h/"
done | sort -r | head -n "$n"
zgrep is grep over a gzip file (it decompresses on the fly); -a forces text mode, -h drops file names. zgrep exits 1 when a batch of files holds no ERROR line, and xargs reports that as 123; under set -e and pipefail that would abort the whole run at the first quiet server, so the remote command ends with || [ $? -eq 123 ]. An ssh failure (exit 255) still stops the script. The guard cannot tell "no ERROR lines" from a truncated or corrupt archive, which also makes zgrep fail and also ends up as 123 (a cut-off .gz prints gzip: logs/x.log.gz: unexpected end of file on stderr), so read stderr as well as the exit status. A file named .gz that is not gzip at all is different: zgrep passes it through as plain text, with no error, and counts any ERROR line in it. In the ssh call, -o BatchMode=yes means ssh never stops to ask for a password or passphrase and fails instead, so a script cannot hang waiting for a person. find ... -print0 | xargs -0 avoids an argument list too long for a single command with 10,000 names. Every byte of every archive is decompressed and every matching line crosses the network.
Faster: newest files first, stop early, merge N per host
On each server (sent over ssh's standard input, so nothing has to be installed there). Reading it: the find ... -printf '%T@\t%p\0' stage prints, for each archive, its modification time as epoch seconds (%T@, seconds since 1970-01-01 UTC, with a fraction), a tab, the path (%p), and a NUL byte (\0) as the end-of-record mark, which is safe for any file name. sort -z -rn sorts those NUL-ended records numerically (-n) and in reverse (-r), so the largest time, the newest archive, comes first. cut -z -f2- then keeps from the second tab-separated field onward, the path, and drops the time. Run on the fixture described below, the first stages print:
1714665540.0000000000 logs/app-39.log.gz
1714661940.0000000000 logs/app-38.log.gz
1714658340.0000000000 logs/app-37.log.gz
(the three newest, before cut) and after cut just logs/app-39.log.gz, logs/app-38.log.gz, logs/app-37.log.gz. In the loop, < <(...) (process substitution) hands the listing to while read as if it were a file, <<<"$hits" (a here-string) feeds the text in $hits to wc -l as its input so the lines can be counted, and read -d '' reads one NUL-ended record at a time. need is how many more lines are still wanted; the loop stops when it reaches 0.
#!/usr/bin/env bash
# Run on each server: last N ERROR lines, reading the newest rotated files first
# and stopping as soon as N lines have been found.
set -euo pipefail
dir=$2 need=$1
[[ -d $dir ]] || { echo "no such directory: $dir" >&2; exit 3; }
while IFS= read -r -d '' f; do
hits=$(zcat -- "$f" | grep -a ' ERROR ' | tail -n "$need" || true)
[[ -n $hits ]] || continue
printf '%s\n' "$hits"
need=$((need - $(wc -l <<<"$hits")))
((need > 0)) || break
done < <(find "$dir" -name '*.log.gz' -printf '%T@\t%p\0' | sort -z -rn | cut -z -f2-)
The driver on your workstation starts one ssh per server at the same time (bash -s -- "$n" logs < tail-errors.sh runs bash on the server with -s, meaning read the program from standard input, and everything after -- becomes that program's arguments, so $1 is N and $2 is logs; it can be tried without ssh as bash -s -- 5 logs < tail-errors.sh), waits for each one, fails loudly if any host failed (a missing host would otherwise give an answer that is silently wrong), and merges. The per-server script first checks that the log directory exists and exits 3 if it does not, so a reachable host with the wrong path also fails the run instead of quietly returning nothing:
#!/usr/bin/env bash
# Usage: search.sh N host... (needs ISO 8601 UTC timestamps at the start of each line)
set -euo pipefail
n=$1
shift
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
pids=()
for h in "$@"; do
ssh -o BatchMode=yes "$h" bash -s -- "$n" logs <tail-errors.sh >"$tmp/$h.raw" &
pids+=($!)
done
rc=0
for p in "${pids[@]}"; do wait "$p" || rc=1; done
((rc == 0)) || {
echo "a host failed; result would be incomplete" >&2
exit 1
}
for h in "$@"; do sed "s/\$/ host=$h/" "$tmp/$h.raw"; done | sort -r | head -n "$n"
Results
The two programs were run over real ssh sessions to two accounts that stand in for two servers (each with 40 hourly archives, 80 files total) and returned identical output for N = 5:
2024-05-02T15:57:00Z ERROR request handled host=web1
2024-05-02T15:54:01Z ERROR request handled host=web2
2024-05-02T15:45:00Z ERROR request handled host=web1
2024-05-02T15:38:01Z ERROR request handled host=web2
2024-05-02T15:36:00Z ERROR request handled host=web1
How many archives the fast path opens depends on how many ERROR lines each archive holds. To make that checkable, the per-server script was run as bash -s -- N logs < tail-errors.sh against a rebuilt fixture of 40 hourly archives (illustrative data). Their ERROR counts, newest archive first, are 6, then seventeen archives of 5, then 9, then twenty archives of 3, then 1: 6 + 85 + 9 + 60 + 1 = 161 ERROR lines. A stand-in zcat that logged each archive name counted the archives opened. The rule is: open archives newest first until the running total reaches N. For N = 5 the newest archive alone has 6, so 1 archive. For N = 100 the running total is 6 + 17 x 5 = 91 after 18 archives and 91 + 9 = 100 after the 19th, so 19. For N = 100,000 the total never reaches N, so all 40 are read and 161 lines return:
| N | Archives opened (of 40) |
|---|---|
| 5 | 1 |
| 100 | 19 |
| 100,000 (more than exist) | 40, all of them |
The brute-force version opens all 40 every time. When N exceeds the number of errors that exist, the fast path degrades to brute force and is still correct.
Cost reasoning
Let F be the number of files, S the average compressed size, H the number of servers. Bytes read by brute force are F x S, and every ERROR line is transferred. Suppose (an assumption for illustration) F = 10,000, S = 40 MB and H = 8 servers:
- Brute force reads 10,000 x 40 MB = 400,000 MB = 400 GB (50 GB per server) and decompresses all of it.
- Fast path with N = 100, if each server's newest archive already has 100 errors: 8 x 40 MB = 320 MB read in total, and at most 8 x 100 = 800 lines transferred.
- The ratio is 400,000 / 320 = 1,250 times less data read. If errors are rare so that each server needs k archives, it is 8 x k x 40 MB, still proportional to k.
Servers run in parallel, so elapsed time is set by the slowest server rather than the sum.
Pitfalls
- Ordering assumptions. The early stop is only valid if newer files contain only newer lines. If a service writes to old files late, or if you rotate by size across several workers, take the file order from the timestamps inside (or from the rotation names) rather than from the file modification time.
- Clock skew. The merge sorts by the line's own timestamp, so hosts with different clocks interleave wrongly. Keep servers on time sync.
- Partial failure.
wait "$p"on each background ssh makes a failed host abort the run (tested with an unresolvable host name: the driver printeda host failed; result would be incompleteand exited with status 1). The same happened for a reachable host whoselogsdirectory was missing (the script exited 3). A healthy host whose archives hold no ERROR line at all exits 0 and contributes nothing, which is correct (tested with three archives holding only INFO lines). One gap remains: a corrupt archive on a reachable host is reported on stderr (gzip: logs/bad.log.gz: not in gzip format) and skipped, because the|| truein the loop hides the failure, so that host exits 0 and its result can be incomplete; watch the stderr of the run. - File names. The listing is NUL-separated, so names with spaces or newlines are safe.
- Tool versions on the servers. The remote script relies on GNU
find -printf,sort -zandcut -z; BusyBox or BSD userlands need a different listing step. - When to stop doing this at all. If this query runs often, ship logs to a central store with an index (a log-search system); the shell approach is right for an occasional investigation.
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.
Unlock Full Question Bank
Get access to all 20 Shell Scripting and Automation interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.