Shell scripting and command-line utilities
This domain, Shell scripting and command-line utilities, tests writing small, correct scripts: quoting, exit status, tests, loops, functions, redirection, and making failures visible instead of silent.
Shell rules
- Start with
#!/bin/bash, or#!/bin/shfor POSIX-only syntax.bash -n scriptchecks syntax andbash -x scripttraces execution. - Variables:
name=valuewith no spaces around=, referenced as$nameor${name}. Quote expansions as"$var"so spaces and empty values survive. Command substitution uses$(cmd). - Positional parameters:
$1,$#,$0, and"$@", where quoting preserves argument boundaries. - Tests:
[ -f file ],[ "$x" = y ], and[[ ... ]]in bash for pattern matching. Numeric comparisons use-eq,-lt, and-gt. - Control flow:
if/elif/else,case,for f in *.log, andwhile read -r line. - Exit status: 0 is success and 1 to 255 are failures;
$?holds the last status.set -euo pipefailexits on errors, rejects unset variables, and propagates pipeline failures.
Worked example
#!/bin/bash
set -euo pipefail
threshold=90
usage=$(df --output=pcent / | tail -1 | tr -dc '0-9')
if (( usage > threshold )); then
echo "root filesystem at ${usage}%" >&2
exit 1
fi
Reasoning: df --output=pcent prints a header plus a percentage, tail -1 takes the data line, and tr -dc '0-9' strips the percent sign. (( )) performs arithmetic comparison, and the message goes to stderr with a non-zero exit so cron or monitoring notices.
Traps
- Unquoted
$varinside[ ]when the value is empty. - Using
==inside[ ]insh. - Reading
$?after a pipeline instead of checkingPIPESTATUS. - Running
rm -rf "$dir"/when$diris empty.