Skip to main content
KBY Technologies Logo

Make Mac Admin Scripts Fail Loudly and Clean Up After Themselves With set, trap and mktemp

Mac script reports success after failing halfway? Add set -u, pipefail, trap EXIT and mktemp -d, then test under /bin/bash.

KBY Technologies11 min readTier L115 min
Make Mac Admin Scripts Fail Loudly and Clean Up After Themselves With set, trap and mktemp

Underlined words are defined in the KBY Lexicon. Tap or click one to see what it means.

A script that hits an error and carries on reports success to your MDM while leaving the Mac half configured. Three features stop that.

set -u and set -o pipefail turn silent mistakes into errors, trap ... EXIT runs your cleanup however the script ends, and mktemp -d gives the script a private work folder to clean up. The shell features are documented in the Bash 3.2 manual page that ships with Apple’s developer tools, so they work under /bin/bash. mktemp has its own man page.

The one that catches people out is set -e. It stops the script on a failing command, but the manual lists contexts where it does not. Read the section on what goes wrong before you rely on it.

#How it usually goes with Mac admin scripts

Most fleet scripts start as a few commands pasted from a Terminal window. They run top to bottom, and the script’s exit status is that of the last command, because that is what Bash returns by default. The manual says Bash returns the exit status of the last command executed.

That default hides three problems. A failure in the middle of the script is forgotten if a later command succeeds. A typo in a variable name expands to an empty string and the command runs with the wrong arguments. A failure on the left of a pipe is lost, because a pipeline reports only the last command’s status unless pipefail is on.

Temporary files make it worse. Scripts often write to a fixed name such as /tmp/result.txt and never remove it. Apple’s mktemp page says a predictable name of this kind is easy for an attacker to win a race against, and it recommends mktemp instead. The same page notes that a predictable temporary directory is still open to a denial of service.

The result is a script that looks healthy in the MDM console. The Mac it ran on may hold a stale file, a partial change and a green status. Scripts that run as root from a LaunchDaemon, as in running a root script at boot or on a schedule, fail with nobody watching.

#What to do instead: stop on failure and clean up on exit

The better workflow gives every script the same short header. It makes errors visible, records where they happened, and removes its own mess whichever way the script ends. The order of events is the same every time, as the diagram shows.

Each piece does a separate job, so it helps to know what the Bash 3.2 manual says about it.

  • set -u treats an unset variable as an error during parameter expansion. A non-interactive shell prints a message and exits with a non-zero status.
  • set -o pipefail makes a pipeline return the status of the rightmost command that failed, or zero if every command succeeded. The option is disabled by default.
  • set -e exits when a simple command returns a non-zero status, with exceptions covered below. A trap on ERR, if set, runs before the shell exits.
  • trap ... EXIT runs the command when the shell exits. EXIT and 0 mean the same thing.
  • trap ... ERR runs whenever a simple command has a non-zero exit status, under the same conditions as set -e.
  • mktemp -d makes a directory with a unique name instead of a file. The utility prints the name on standard output and exits non-zero if it fails.

Keep the scripts on the shell every Mac already has. Writing Mac Bash scripts for the Bash 3.2 in /bin/bash explains why you pin #!/bin/bash and test there, not under Homebrew’s Bash.

#Setting it up in a script

Put the header at the top of the script, directly under the shebang. The block below is a complete working skeleton. Replace the lines after log "work dir" with your own work.

1#!/bin/bash
2set -eu
3set -o pipefail
4
5WORKDIR=""
6
7log() { printf '%s %s\n' "$(date '+%Y-%m-%dT%H:%M:%S')" "$*" >&2; }
8
9on_error() { log "ERROR line $1: $2"; }
10
11cleanup() {
12  rc=$?
13  if [ -n "$WORKDIR" ] && [ -d "$WORKDIR" ]; then
14    rm -rf -- "$WORKDIR"
15  fi
16  log "exit $rc"
17  exit "$rc"
18}
19
20trap 'on_error "$LINENO" "$BASH_COMMAND"' ERR
21trap cleanup EXIT
22trap 'exit 143' TERM
23trap 'exit 130' INT
24
25WORKDIR=$(mktemp -d -t kby-example)
26log "work dir $WORKDIR"
27# ... your work goes here ...

Several choices in that block are deliberate. WORKDIR starts as an empty string, so an early failure cannot make the cleanup remove the wrong path. The cleanup function saves $? in its first line, before any other command changes it, and ends with exit "$rc" so the MDM sees the original status.

The TERM and INT traps call exit with 128 plus the signal number. The manual says Bash uses 128+N for a command killed by fatal signal N, and the convention keeps the status honest. Calling exit is what triggers the EXIT trap, so the cleanup runs for those two signals as well.

The man page says mktemp -t prefix builds its template from the prefix and _CS_DARWIN_USER_TEMP_DIR when that is available. The fallbacks are TMPDIR and /tmp. It warns that TMPDIR may come from the user, so decide whether that suits a script that runs as root. For a root script, pass mktemp -d a template in a folder that only root can write to, and the question does not arise.

Give a variable that may legitimately be empty a default with ${NAME:-}. Then set -u flags only the variables you did not mean to leave unset.

Focused shot of a laptop displaying code, suitable for tech and coding themes.
Photo by Oluwaseun Duncan on Pexels

#Keeping it safe on a production Mac

Cleanup code is the part of a script most likely to delete the wrong thing, so give it narrow limits.

  • Only ever remove the path that mktemp returned for this run. Never build the path to delete from user input, a glob or a variable that other code can change.
  • Guard the rm as the skeleton does: the variable must be non-empty and the path must be an existing directory.
  • Do not trap signals you do not need. The Bash manual says signals ignored on entry to the shell cannot be trapped or reset, so a trap on one of those does nothing.
  • Keep the ERR handler read-only. It should log the line and the command, not try to repair anything.
  • Never log secrets. BASH_COMMAND holds the text of the failed command, so a command line that contains a token or password lands in the log.

Run the script from a root-owned location and make the script file writable only by root. A cleanup routine that runs as root is a privileged code path, so an ordinary account must not be able to change the file. The same applies to the work directory. The mktemp man page documents mode 0600 for files, not directories. Run chmod 700 on the folder if it holds anything sensitive.

If the script must act for the logged-in user as well, keep that in a separate step. Running a command as the logged-in user from a root script covers it, and the same header applies to both parts.

#Verifying it worked on a test Mac

Test the header on a Mac or virtual machine you can restore, not on a production Mac. Run each check under /bin/bash, because that is the shell the fleet uses. The first three checks change nothing.

  1. Syntax. Run /bin/bash -n ./script.sh. The -n option reads the commands without executing them. No output and status 0 means no syntax errors.
  2. Unset variable. Run /bin/bash -c 'set -u; echo "$NOT_SET"; echo after'; echo "status $?". You should see an error naming NOT_SET, no after line, and a non-zero status.
  3. Pipe failure. Run /bin/bash -c 'false | cat; echo "plain $?"' and then the same with set -o pipefail; in front. The first prints plain 0 and the second prints plain 1.
  4. Forced failure. Add a deliberate false to a copy of the script and run it on the test Mac. You should see an ERROR line message, then exit 1, and the work directory should be gone.
  5. Termination. Add sleep 60 to the copy, run it, and send kill -TERM to its process from a second Terminal window. The log should end with exit 143 and the folder should be removed.

Following along? Tap a step’s number to tick it off.

The fifth check has a documented wrinkle. If Bash is waiting for a command and receives a trapped signal, the trap does not run until that command completes. The script above therefore stops only after sleep 60 ends. Keep long-running steps short, or run them in the background and use wait, which returns immediately when a trapped signal arrives.

#What goes wrong with set -e

The Bash 3.2 manual lists where set -e does not exit. These are the list after while or until, the test in an if statement, and a && or || list. A command whose status is inverted with ! is also exempt. The ERR trap follows the same conditions. A script that checks if some_command; then will not stop when some_command fails, which is usually what you want.

The current Bash manual goes further. It says that when a function runs where -e is ignored, no command inside it is affected by -e. A function called from an if test or an || list therefore runs to the end after a failure. That text is from the Bash 5.3 manual, so confirm the behaviour on /bin/bash with a short test before relying on it.

These are the mistakes that appear most often in fleet scripts.

  • Assuming a pipeline fails on its first command. Without pipefail, only the last status counts. With it, you get the rightmost non-zero status. The PIPESTATUS array holds every stage’s status, so read it to find which stage failed.
  • Trusting BASH_COMMAND in a pipeline. In a test on Bash 5.2, false | cat reported cat as the command, not false. Use the line number from LINENO and PIPESTATUS to locate the real failure. Check how your target Bash behaves.
  • Letting the cleanup change the exit status. A cleanup function whose last command fails, or that does not end with exit "$rc", can replace a useful status with an unrelated one.
  • Using a variable in the cleanup before it exists. With set -u, a cleanup that reads an unset WORKDIR is itself an error. Initialise it to an empty string before the traps, as the skeleton does.
A close-up of a laptop with stickers on a wooden table situated in a home office setting.
Photo by cottonbro studio on Pexels

#Backing out a bad script version

A stricter header can stop a script that used to finish with status 0 despite a harmless error. Plan for that before the pilot.

  1. Keep the previous version of the script in your MDM or in version control, tagged, so it can be assigned again in minutes.
  2. If a pilot Mac reports failures, unassign the new version from the pilot group and assign the previous one to the same group.
  3. Read the log line that the ERR trap wrote. It names the line number and the command, which is usually enough to see whether the failure was real or only a newly visible one.
  4. If a failed run left a work folder behind, remove only the folder that matches your prefix, once nothing is using it.
  5. Fix the script, retest on the test Mac, and send it to the pilot group again.

Do not roll back by deleting set -e across the fleet to make errors go away. That restores the old behaviour in which failures are silent.

#How to tell it worked across the fleet

Success is that failures become visible and Macs stop collecting leftovers. Measure those two things for the scripts you convert, and compare them with the weeks before the change.

  • The number of runs the MDM reports as failed. This should rise at first, because errors that were hidden now show up, and then fall as you fix their causes.
  • The number of Macs with leftover work folders. A read-only check that counts matching folders in the temporary directory should trend to zero.
  • The share of failed runs whose log names a line number. It should reach 100 per cent, because every failure now goes through the ERR trap.

Review these numbers after each script release and after each major update. Apple’s mktemp page is dated 2005 and the Bash 3.2 page is dated 2006. Run /bin/bash --version on a test Mac after each major macOS release to confirm the shell your scripts target has not changed.

#Before you roll it out

  1. The script starts with #!/bin/bash and passes /bin/bash -n.
  2. The header sets -u and pipefail, and you have decided deliberately whether to use -e.
  3. Every EXIT path, including TERM and INT, was tested and removes the work directory.
  4. The cleanup deletes only the directory mktemp returned, behind the two guards.
  5. The script exits with the original status, and you confirmed it in the MDM on a test Mac.
  6. The previous version is tagged and ready to reassign to the pilot group.
  7. The log does not contain secrets, even when a command fails.

About this page

Credited to

Dates

Published

Sources

This page lists no external sources.

Corrections

No corrections are listed for this page. Some review sweeps corrected pages without naming each one; those are in the corrections log.

Found this useful? Follow KBY for more like it.

Reader Interaction

Comments

Add a thoughtful note on Make Mac Admin Scripts Fail Loudly and Clean Up After Themselves With set, trap and mktemp. Comments are checked for spam and held for moderation before appearing.

Loading comments...

More from KBY that goes with this article.

Discover more

Was this useful?

Reports go to the site owner and are used to correct pages. Corrections are listed at /corrections.

Operate smarter, with fewer recurring tickets.

Receive new operational playbooks, incident-prevention guidance, automation scripts and recovery runbooks.