CELE study materials
CELE study resources

CELE: Shell scripting and command-line utilities

CELE · Work through your exam, one topic at a time.

All guide sections

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/sh for POSIX-only syntax. bash -n script checks syntax and bash -x script traces execution.
  • Variables: name=value with no spaces around =, referenced as $name or ${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, and while read -r line.
  • Exit status: 0 is success and 1 to 255 are failures; $? holds the last status. set -euo pipefail exits 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 $var inside [ ] when the value is empty.
  • Using == inside [ ] in sh.
  • Reading $? after a pipeline instead of checking PIPESTATUS.
  • Running rm -rf "$dir"/ when $dir is empty.