Skip to content

Lesson 4 of 9 · 23m

Shell Automation with zsh That Survives Production

Write small, idempotent zsh automation with correct quoting, error behavior, privilege boundaries, and machine-readable output.

The worst Mac automation I inherited was a 900-line shell script named fix.sh. It half-configured machines, deleted logs it needed, and could not be run twice without breaking the docking setup. Good macOS shell automation is boring: small tools, strict modes, explicit inputs, idempotent behavior, and output you can ingest.

zsh is the default shell, not bash compatibility theater

macOS ships zsh as the default interactive and scripting shell. Start scripts with #!/bin/zsh and set -euo pipefail.

pipefail makes a failing command in a pipeline fail the pipeline. nounset behavior under set -u catches unset variables, but remember that optional positional parameters need defaults:

serial=${1:-}
if [[ -z "$serial" ]]; then
  print -u2 'usage: check-device.zsh SERIAL'
  exit 64
fi

Use print rather than echo when output consistency matters, especially with escape characters.

Quote like filenames are hostile — because they are

Paths under /Users contain spaces, apostrophes, Unicode, and occasionally creative disaster. This is the difference:

if [[ -d "$target_dir" && "$target_dir" == /var/tmp/enrollment-cache/* ]]; then
  command rm -rf -- "$target_dir"
fi

Use -- to terminate option parsing where supported. Construct commands in arrays and invoke them as "${cmd[@]}" rather than flattening them into strings.

Make scripts idempotent

A script should converge the machine toward desired state, not perform blind mutation. Check before changing:

desired=1
current=$(/usr/bin/defaults read com.apple.screensaver askForPassword 2>/dev/null || print 0)
if [[ "$current" != "$desired" ]]; then
  /usr/bin/defaults write com.apple.screensaver askForPassword -int "$desired"
fi

Defaults are not always the correct management mechanism — many security settings belong in profiles — but the pattern matters: observe, compare, then mutate.

Separate local admin from MDM execution context

Scripts launched by MDM often run as root with no user session context. User preferences, keychain items, TCC state, and GUI behavior may not exist in that context. Write scripts that declare their expected domain and fail early when, for example, $USER is not root for a system-level mutation.

Field notes

  • /bin/sh on macOS is not a promise of Linux shell semantics. Test on macOS, not only in a container.
  • Avoid parsing human-oriented output when a machine-readable mode exists: many tools support -json or plist output.
  • Exit codes are an operational interface. Use 0 success, nonzero failure, and consistent usage errors.
  • Do not hide destructive action inside broad cleanup logic. Log the exact path or object before changing it.

Was this lesson helpful?

Sign in to rate