Logging, Verbosity and Dry-Run Modes

Logging, Verbosity and Dry-Run Modes in Bash: --- During a live theatre performance the stage manager sits at the prompt desk with a headset and a marked-up…


The Analogy: The Stage Manager's Cue-Calling and Show Report

During a live theatre performance the stage manager sits at the prompt desk with a headset and a marked-up script, calling every cue -- "LX 42 go, fly the backdrop, sound cue 11 go". Those calls travel on a closed comms ring heard only by the crew: the lighting board operator, the flyman, the sound engineer. The audience hears none of it; they experience only the show itself. This split is the heart of good script logging. The diagnostics -- what the program is doing and why -- go on a private channel (standard error), while the result the outside world consumes -- the report, the processed file, the number -- goes on the public channel (standard output). Mixing the two is like calling cues over the auditorium speakers.

Not every call carries the same weight. The stage manager's show report distinguishes a routine note ("house opened at 19:28") from a warning ("understudy on for Act 2") from an incident ("LX 42 failed to fire, called it verbally"). A well-run desk lets the SM dial how much of this chatter reaches the ring: during a technical rehearsal every tiny adjustment is spoken aloud, while during the run only warnings and incidents break the quiet. Log levels are exactly this severity scale -- DEBUG, INFO, WARN, ERROR -- and verbosity is the dial that decides how far down the scale the chatter is allowed to reach.

Before opening night there is a technical dress: the company walks the entire show, the SM calls every cue in real time, the board operators acknowledge -- but the pyrotechnics are spoken, not fired, and the heavy scenery moves are called and timed without actually flying anything dangerous over people's heads. Nothing irreversible happens, yet everyone proves they know their part and the timing holds together. A dry-run mode is that technical dress for a script: it announces every destructive action it would take -- "would delete build/, would copy to dist/" -- and executes none of them, so an operator can prove the plan is right before letting it touch real files.

The failure mode is the diagnostic that leaks onto the public channel. If the SM, flustered, calls a warning over the front-of-house PA instead of the comms ring, the audience hears "understudy on, and mind the gap in the rostra" mid-scene, and the illusion collapses. When a script prints its log lines to standard output instead of standard error, the same contamination happens downstream: a command that pipes the script into jq or sort suddenly finds [INFO] processing... lines mixed into what was supposed to be clean data, and the next stage either errors or, worse, silently treats the log line as a record. Keeping the two channels separate is not tidiness; it is what makes a script safe to compose with others.


Syntax or Core Structure

The foundation is a log function that writes to standard error, leaving standard output free for real results. A minimal version prints a level tag and the message:

log() { printf '[%s] %s\n' "$1" "${*:2}" >&2; }

log INFO "processing 3 records"
echo "result=42"

Here $1 is the level and ${*:2} is every argument after it, joined into the message. The >&2 sends the line to file descriptor 2 (standard error), while the echo writes the actual result to descriptor 1 (standard output). Because the two streams are independent, a caller can keep just the data by discarding standard error:

bash script.sh 2>/dev/null

Output:

result=42

Or inspect only the diagnostics by discarding standard output:

bash script.sh 1>/dev/null

Output:

[INFO] processing 3 records

That clean separation is what lets script.sh | jq . work: jq receives result=42 and nothing else, because every log line went to the private channel. Send the logs to standard output instead and the pipeline breaks the moment it meets a message.


Technical Depth: Levels, the Verbosity Dial, and Dry-Run Wrappers

A severity scale and a threshold

Levels are only useful if the script can suppress the ones below a chosen floor. Map each level to a number and compare against a threshold held in LOG_LEVEL:

LevelRankUse it for
DEBUG0tracing values, loop internals
INFO1normal progress milestones
WARN2recoverable trouble, retries
ERROR3failures the operator must see
LOG_LEVEL="${LOG_LEVEL:-INFO}"
declare -A LEVELS=([DEBUG]=0 [INFO]=1 [WARN]=2 [ERROR]=3)
log() {
  local level="$1"; shift
  (( LEVELS[$level] >= LEVELS[$LOG_LEVEL] )) || return 0
  printf '[%s] %s\n' "$level" "$*" >&2
}
log DEBUG "connecting to db"
log INFO  "server started"
log WARN  "retry 1 of 3"
log ERROR "giving up"

With the default threshold of INFO, the DEBUG line is below the floor and never prints:

[INFO] server started
[WARN] retry 1 of 3
[ERROR] giving up

Raise the floor to WARN (run with LOG_LEVEL=WARN) and the progress noise disappears too, leaving only what an operator needs during a quiet production run:

[WARN] retry 1 of 3
[ERROR] giving up

Verbosity as a dial

Rather than make the user type LOG_LEVEL=DEBUG, scripts usually expose a -v flag that can be repeated, each occurrence turning the dial one notch louder. Counting the flags is a plain loop:

verbosity=0
for a in "$@"; do [ "$a" = "-v" ] && verbosity=$(( verbosity + 1 )); done
echo "verbosity=$verbosity"

Passing -v -v yields:

verbosity=2

You then translate the count into a floor: 0 stays at WARN, one -v drops to INFO, two or more to DEBUG. A matching -q (quiet) flag raises the floor to ERROR for cron jobs that should stay silent unless something breaks.

Translating the dial into a floor

The count only matters once it becomes a threshold. A case turns the number into a level name the log function can compare against, which keeps the mapping in one obvious place instead of scattered if tests:

verbosity=2
case "$verbosity" in
  0) floor=WARN ;;
  1) floor=INFO ;;
  *) floor=DEBUG ;;
esac
echo "verbosity=$verbosity floor=$floor"

Output:

verbosity=2 floor=DEBUG

Two -v flags reach the noisiest floor; a bare invocation stays at WARN, so an unattended run says nothing unless it must. Because the mapping is a single case, adding a -q that forces floor=ERROR is a one-line change, and the log function never has to know how the floor was chosen -- it only compares ranks.

Copying logs to a file

Diagnostics that vanish with the terminal are no use after an overnight run. Piping each log line through tee -a writes it to a file and forwards it to standard error, so someone watching live and someone reading the file the next morning both get the same record:

: > run.log
log() { printf '[%s] %s\n' "$1" "${*:2}" | tee -a run.log >&2; }
log INFO "step one"
log WARN "step two slow"

After the run, run.log holds exactly the lines that were emitted:

[INFO] step one
[WARN] step two slow

For a script that should capture everything from the outset, redirect standard error once at the top with exec 2> >(tee -a run.log >&2); every later log call is then recorded without changing a single call site. In production you would also prefix each line with date '+%F %T' so the file records when each step happened -- it is omitted here only to keep the output stable enough to compare byte for byte.

Wrapping side effects for dry-run

A dry-run mode needs a single choke point that every destructive command passes through. The run wrapper either executes its arguments or merely announces them:

run() {
  if [ "$DRY_RUN" -eq 1 ]; then
    log INFO "would run: $*"
  else
    log INFO "running: $*"
    "$@"
  fi
}

The discipline this demands is absolute: a command that does not go through run still executes in dry-run. That is the crack the real-world example falls through.


Real World Example: A Deploy Script with Dry-Run

The script below publishes a build directory to a destination, routing every file-changing command through run so that --dry-run can preview the whole plan without touching disk. Logging goes to standard error, leaving standard output clean.

#!/usr/bin/env bash
# deploy.sh -- publish a build directory, with logging and a --dry-run mode
set -euo pipefail

DRY_RUN=0
[ "${1:-}" = "--dry-run" ] && { DRY_RUN=1; shift; }

log() { printf '[%s] %s\n' "$1" "${*:2}" >&2; }

run() {
  if [ "$DRY_RUN" -eq 1 ]; then
    log INFO "would run: $*"
  else
    log INFO "running: $*"
    "$@"
  fi
}

SRC="${1:-build}"
DST="${2:-dist}"

run mkdir -p "$DST"
run cp -a "$SRC/." "$DST/"
run rm -rf "$SRC"
log INFO "done"

Invoked with --dry-run, it narrates the plan on standard error and changes nothing on disk:

bash deploy.sh --dry-run build dist

Output:

[INFO] would run: mkdir -p dist
[INFO] would run: cp -a build/. dist/
[INFO] would run: rm -rf build
[INFO] done

Drop the --dry-run and the same three commands run for real: dist/ is created, the build is copied in, and the source tree is removed -- each announced with running: instead of would run:. The value is that an operator can read the dry-run output, confirm that rm -rf build targets the directory they expect and not /, and only then commit. The logging and the preview together turn an irreversible operation into a reviewable one.

The safety, though, is only as good as the rule that every effect goes through run, and that rule has a hole the wrapper cannot close: redirections. Write run generate > out.json and the shell opens and truncates out.json before run is ever called, so under --dry-run the file is still created and emptied even though the generator never executes -- the preview lies. The same is true of cd, of $(command substitution) used for its side effects, and of any pipeline the author forgot to route through the wrapper.

The second flaw is quieter. In dry-run, run always returns success, so a script that branches on a command's exit status (if run check ...; then) takes the success path unconditionally during a preview, exercising code that would never run in reality. A dry-run therefore proves the sequence of intended commands but not the control flow around them; treating a clean dry-run as proof that the real run will follow the same path is a mistake the deploy script quietly invites.


Common Mistakes

  1. Logging to standard output. Diagnostic lines on stdout contaminate any pipeline that consumes the script's real output. Send every log line to standard error with >&2 and reserve stdout for data.
  1. Having no levels at all. A script that prints everything or nothing gives the operator no dial. Even a two-level split (normal versus verbose) is far better than a wall of undifferentiated echo.
  1. Messages without context. log ERROR "failed" tells the reader nothing. Name the subject and the cause: log ERROR "upload of $file failed: no space on $dest". A log is only worth writing if it is worth reading later.
  1. A dry-run that is not complete. If some commands go through run and others do not, --dry-run executes the unguarded ones for real. Redirections, cd, and command substitutions are especially easy to leave outside the wrapper.
  1. Formatting with echo -e instead of printf. Whether echo interprets \n or treats -e as text varies between shells and builds. printf '[%s] %s\n' ... is portable and predictable; use it for every log line.
  1. Making verbosity a toggle, not a scale. A single on/off -v cannot express "a bit more" versus "trace everything". Count repeated -v flags and map the count onto the level floor so users can choose how loud.
  1. Omitting timestamps from logs that outlive the terminal. A line in a log file with no time is nearly useless for diagnosis. Prefix file-bound logs with date '+%F %T'; you can leave the timestamp off only for output that a test will compare byte for byte.
  1. Swallowing the real exit status. Piping a command into tee or logging after it (cmd; log INFO done) discards cmd's status. Capture $? or set -o pipefail so a logged step can still fail the script.
  1. Over-logging at INFO. If every trivial step is INFO, genuine warnings drown in the stream and the level scale stops meaning anything. Push routine tracing down to DEBUG and keep INFO for milestones a human would want to see.

Best Practices

  • Send logs to stderr, data to stdout. Make the separation a rule from the first line so the script is safe to place in a pipeline without special handling.
  • Use a level scale with a tunable floor. Rank DEBUG through ERROR, hold the threshold in LOG_LEVEL, and suppress anything below it so the same script is quiet in production and chatty in debugging.
  • Expose a repeatable -v and a -q. Let users dial verbosity up with each -v and force silence with -q, then translate both into the level floor.
  • Timestamp file-bound logs. Prefix lines destined for a log file with date '+%F %T'; omit it only where a test needs deterministic, byte-stable output.
  • Route every side effect through one run wrapper. A single choke point is what makes --dry-run trustworthy; guard redirections explicitly, since the shell performs them before the wrapper sees anything.
  • Format with printf, never echo -e. Predictable output across shells matters most in exactly the diagnostic code you reach for when something is already wrong.
  • Write messages a stranger could act on. Name the subject, the action, and the reason in each line, so a log read weeks later still explains itself.
  • Never let logging hide a failure. Preserve exit status with $? or set -o pipefail so that adding diagnostics can only make failures more visible, never less.

Practice Exercises

  1. Split the channels. Write a script that prints one data line to standard output and three log lines to standard error. Show that running it with 2>/dev/null leaves only the data and with 1>/dev/null leaves only the logs, and explain why that makes the script pipeline-safe.
  1. Add a threshold. Extend a log function with a LOG_LEVEL floor backed by an associative array of ranks. Demonstrate that a DEBUG message is suppressed when the floor is INFO, and that an INFO message is suppressed when the floor is WARN.
  1. Dial the verbosity. Parse repeated -v flags into a count and map 0, 1, and 2 onto WARN, INFO, and DEBUG; add a -q that forces the floor to ERROR. Show the resulting level for the arguments -v -v and for -q.
  1. Expose the dry-run hole. Add a step to the deploy script that uses a redirection, such as run generate > out.json. Run the script with --dry-run, show that out.json is created and emptied anyway, then rewrite the step so the redirection is guarded by the dry-run check rather than performed unconditionally.