Skip to main content

Write Mac Bash Scripts for the Bash 3.2 in /bin/bash, Not Your Homebrew Bash

Mac Bash script works in Terminal but fails in MDM? Pin #!/bin/bash, replace Bash 4 features like declare -A, and test with bash -n and env -i.

KBY Technologies11 min readTier L115 min
Write Mac Bash Scripts for the Bash 3.2 in /bin/bash, Not Your Homebrew Bash

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

A script that runs cleanly in your Terminal can still fail when your MDM runs it on the fleet. One cause that is easy to miss is that your Terminal found a newer Bash than the one at /bin/bash.

The fix is to write for the shell every Mac already has. Make the first line #!/bin/bash, not #!/usr/bin/env bash, and leave out anything Bash 4 or later added. The bash manual page that comes with Apple’s developer tools is the GNU Bash 3.2 manual, dated 28 September 2006. Homebrew’s bash formula is at 5.3.20 in November 2026. A script tested with Homebrew’s Bash can therefore use features /bin/bash does not have, such as declare -A, mapfile and ${name,,}. Check each script with /bin/bash -n, then run it as root on a clean test Mac before the MDM sees it.

#Why the script works today on your Mac and nowhere else

Since 10.15, new user accounts use zsh as the login and interactive shell. Bash is still at /bin/bash. If you install Homebrew, it goes to /opt/homebrew on Apple silicon. Its setup asks you to add a brew shellenv line to your shell’s config file, such as ~/.zshrc, so that your shell finds Homebrew’s programs.

After brew install bash, typing bash in your Terminal can start Homebrew’s 5.x Bash. A script that starts #!/usr/bin/env bash does the same, because env finds the interpreter by searching PATH. The env manual page names the catch: that line assumes the PATH will find the interpreter you want. An MDM agent or a LaunchDaemon starting your script as root does not read your ~/.zshrc. If you have built root jobs like the ones in running a root script at boot or on a schedule with a LaunchDaemon, the PATH they get is not your Terminal’s.

So the script reaches the fleet and runs under /bin/bash. The worst case is a script that fails without an error you would notice. Bash 3.2’s declare accepts only the -a, -f, -F, -i, -r, -t, -x and -p options. Given -A, it fails with a usage error and a non-zero status. Without set -e, the script carries on.

The next line, say map[wifi]=..., then treats map as an ordinary indexed array. In Bash 3.2 a subscript is an arithmetic expression, and a word that names an unset variable evaluates to 0. Keys such as wifi and vpn all land in element 0. Every lookup returns whichever value was written last. Apart from that one declare line, nothing complains, and a script’s exit status is that of its last command. A tool that only reads the exit status can record success.

The usual workaround is to install Homebrew’s Bash on every Mac, or to point the shebang at /opt/homebrew/bin/bash. Every script now depends on Homebrew being installed and healthy before it can start. Homebrew installs to that prefix so that installing formulae needs no sudo afterwards. A root script would then run an interpreter that the account which installed Homebrew can replace without sudo.

#The better way is to write for the shell the fleet already has

Treat /bin/bash as the target, not your Terminal. The workflow has four rules:

  1. Every Bash script for the fleet starts #!/bin/bash. The system runs the interpreter named on that line, so the result no longer depends on PATH.
  2. Write to the Bash 3.2 manual. For anything you learnt from a newer Bash, check which release added it in the Bash NEWS file before you use it.
  3. Check every change with a syntax check and a scan for Bash 4 features.
  4. Run the script as root on a clean test Mac with a plain system PATH, then on a pilot group, before the whole fleet.

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

The same thinking applies to scripts that start #!/bin/sh. On macOS, sh re-executes itself as bash, dash or zsh, depending on the symbolic link at /private/var/select/sh. Apple warns that if that link points anywhere other than bash, scripts that use bashisms may not work. A script that needs Bash features should say #!/bin/bash and not rely on that link.

#Step by step on one script

Work on a test Mac or a virtual machine you can restore. Nothing in the first three steps changes the Mac.

#
Read what each Mac will actually run

  1. Run /bin/bash --version. Expect a version line for Bash 3.2.
  2. Run command -v bash. If it prints /opt/homebrew/bin/bash, your Terminal’s bash is not the fleet’s.
  3. Run head -n 1 ./script.sh. Expect #!/bin/bash. Stop and fix the first line if it shows env or sh.
  4. Run readlink /private/var/select/sh. It prints the shell that sh runs on this Mac. You only need it for scripts that start #!/bin/sh.
A laptop surrounded by books and scripts on a wooden desk, perfect for literature and technology themes.
Photo by Ron Lach on Pexels

#
Find the Bash 4 features

Scan the script with grep. The pattern catches the common features in the table below. It is a coarse net, so read the script too.

grep -nE 'declare -[a-zA-Z]*[An]|mapfile|readarray|,,}|\^\^}|\|&|&>>|coproc|wait -n|\[-[0-9]+]' ./script.sh

grep prints each matching line with its line number and exits 0 when it finds one. Exit status 1 means no line matched. Any match is a stop condition: rewrite that line before you go further.

#
Replace them with Bash 3.2 equivalents

At a glance

Added in vs Write this for Bash 3.2

declare -A associative arrays
Added in
Bash 4.0
Write this for Bash 3.2
A function with a case statement, or two indexed arrays searched in a loop
mapfile and readarray
Added in
Bash 4.0
Write this for Bash 3.2
while IFS= read -r line; do lines+=("$line"); done < file
${name,,} and ${name^^}
Added in
Bash 4.0
Write this for Bash 3.2
printf '%s' "$name" | tr '[:upper:]' '[:lower:]'
cmd |& next
Added in
Bash 4.0
Write this for Bash 3.2
cmd 2>&1 | next
cmd &>> file
Added in
Bash 4.0
Write this for Bash 3.2
cmd >> file 2>&1
${a[-1]} negative subscripts
Added in
Bash 4.3
Write this for Bash 3.2
${a[${#a[@]}-1]} for an array with no gaps
coproc, declare -n, wait -n
Added in
Bash 4.0, 4.3, 4.3
Write this for Bash 3.2
No direct equivalent; redesign the step
Bash 4 and later features, the release that added them, and what to write for the Bash 3.2 in /bin/bash

Here is what the replacements look like in a script. The case function returns a non-zero status for an unknown key, so the caller can test for it. The read loop stops at end of file, so make sure the list ends with a newline or its last line is skipped.

1# Bash 3.2: a function lookup instead of declare -A
2profile_for() {
3  case "$1" in
4    wifi) echo "com.example.wifi" ;;
5    vpn)  echo "com.example.vpn" ;;
6    *)    return 1 ;;
7  esac
8}
9
10# Bash 3.2: a read loop instead of mapfile
11lines=()
12while IFS= read -r line; do
13  lines+=("$line")
14done < /path/to/list.txt
15
16# Bash 3.2: the last element without a negative subscript
17if [ "${#lines[@]}" -gt 0 ]; then
18  last="${lines[${#lines[@]}-1]}"
19fi
20
21# Bash 3.2: lower case with tr instead of ${name,,}
22name_lower=$(printf '%s' "$name" | tr '[:upper:]' '[:lower:]')

Put a short guard at the top as well. It stops the script if something other than Bash runs it, and it writes the Bash version into the MDM log as evidence.

1#!/bin/bash
2if [ -z "${BASH_VERSION:-}" ]; then
3  echo "Run this script with /bin/bash" >&2
4  exit 1
5fi
6echo "Running under bash ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}"

#
Syntax check, then run it the way the fleet will

Run /bin/bash -n ./script.sh. With -n, Bash reads the commands without running them, to check for syntax errors. Expect no output and exit status 0. A syntax error makes Bash exit with a non-zero status.

Next, run the script for real on the test Mac. This step changes whatever the script changes, so take a snapshot of the virtual machine or a of the test Mac first. Then run:

sudo env -i PATH=/usr/bin:/bin:/usr/sbin:/sbin /bin/bash ./script.sh; echo "exit $?"

env -i throws away your inherited environment, so the only PATH is the plain system one you give it. Expect the guard’s “Running under bash 3.2” line, the output you designed, and “exit 0”. Any other exit status is a stop condition. Restore the snapshot before each new attempt.

#Who can change fleet scripts

  • Keep fleet scripts in version control. A change reaches the MDM only after a second admin has read the diff and the test output.
  • Limit who can upload or assign scripts in the MDM to the people who manage it.
  • Never point a root script at an interpreter in a folder an ordinary account can write to, such as Homebrew’s prefix.
  • Leave /private/var/select/sh alone on production Macs. Apple describes changing it as a way to test scripts, and it changes what every #!/bin/sh script on that Mac runs under.
  • Use set -o pipefail where a pipeline’s failure matters. Bash 3.2 has it, off by default.
Open MacBook Air with apps and web browser on screen, placed on a wooden table indoors.
Photo by Abdullah Bin Mubarak on Pexels

#Check it worked on a clean test Mac

  1. The syntax check exits 0 and the grep scan exits 1.
  2. The test run prints the guard line with major version 3 and ends “exit 0”.
  3. For every lookup you ported from declare -A, each key returns its own value. An unknown key returns a non-zero status.
  4. On the pilot group, the MDM records exit status 0 for the new version on every Mac that ran it.

If the script runs from launchd, read its log lines as described in triaging launchd log noise at the login window.

#What goes wrong when porting to Bash 3.2

  • The declare -A collision described above. The script runs, every key returns the same value, and the MDM can still record success. Only a test that checks each key catches it.
  • Negative subscripts. Bash 3.2 needs a subscript of 0 or more, so ${a[-1]} must become ${a[${#a[@]}-1]}. Guard against an empty array first.
  • Redirection shortcuts. |& and &>> arrived in Bash 4.0. Write 2>&1 | and >> file 2>&1.
  • Testing by pasting lines into a Terminal that runs zsh. zsh is mostly compatible with Bash, with some differences, so it proves nothing about /bin/bash.
  • Case conversion with tr. It follows the case mapping of the current locale, so test with the same environment the fleet uses if names can contain non-ASCII letters.
  • Bash features in a #!/bin/sh script. They work while /private/var/select/sh points at bash and may stop working if it changes.

#Roll back to the previous script version

Before the pilot, keep the previous script in version control and the previous version in the MDM.

  1. If pilot Macs report a non-zero exit, unassign the new version and assign the previous one to the same group.
  2. Undo whatever the new version changed on those Macs. That depends on the script, so write the undo steps before the pilot, not after.
  3. Revert the commit in version control, so the next change starts from the version that worked.
  4. Confirm the rollback: the MDM shows the previous version ran on each pilot Mac with exit status 0.

On the test Mac, restore the snapshot taken before the test run. Nothing in this playbook changes /bin/bash, the system shells or /private/var/select/sh, so there is nothing else to undo.

#What to track after the change

  • The number of fleet scripts whose first line is #!/bin/bash, against the total. Count with grep across your repository.
  • The number of scan hits across all scripts, which should fall to zero and stay there.
  • MDM script runs with a non-zero exit status each week, before and after the change.
  • The guard’s Bash version line in MDM logs.

Review the counts monthly at first, then each quarter. After each major macOS release, run /bin/bash --version on a test Mac before the release reaches the fleet.

#Before you switch the fleet over

  • The first line is #!/bin/bash.
  • The grep scan exits 1 and /bin/bash -n exits 0.
  • The test run as root with a system PATH ends “exit 0”, and every ported lookup returns the right value.
  • A second admin has reviewed the diff and the test output.
  • The previous version is still in the MDM, and the undo steps for this script are written down.
  • The pilot group has run it with exit status 0.

If a script needs something Bash 3.2 cannot do, such as a coprocess or a name reference, the next safe decision is to rewrite it for /bin/zsh, which Apple includes, rather than to install a newer Bash. Give it the same test run and pilot.

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.

Reader Interaction

Comments

Add a thoughtful note on Write Mac Bash Scripts for the Bash 3.2 in /bin/bash, Not Your Homebrew Bash. Comments are checked for spam and held for moderation before appearing.

Loading comments...

Operate smarter, with fewer recurring tickets.

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