brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: BASH_VERSINFO stops a script that needs a newer bash than macOS ships

Bash
~/tips/tip-bash-versinfo-check

echo "needs bash 4 or newer, this is $BASH_VERSION" >&2

Fail early with a clear message when bash is too old for your script.

macOS still comes with bash 3.2, so a script with declare -A or mapfile that runs fine on Linux crashes with odd errors on a Mac. A check at the top turns that into one clear message.

BASH_VERSINFO is an array with the version parts as numbers. Index 0 is the major version, index 1 the minor:

if (( BASH_VERSINFO[0] < 4 )); then
  echo "needs bash 4 or newer, this is $BASH_VERSION" >&2
  exit 1
fi

For a feature that arrived in a minor release, check both parts, for example bash 4.4 for inherit_errexit:

(( BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 4) )) || exit 1

I like this better than parsing bash --version, which starts another program and gives you the version of whichever bash is first on PATH, not the one running your script.

Run the check before anything that uses new syntax, because bash parses a whole function or compound command before it runs it. On a Mac with Homebrew bash, also start the script with #!/usr/bin/env bash so it picks up the newer one. On Debian or Ubuntu, sh script.sh runs dash instead of bash, and there the variable is simply empty.

Further reading: Bash manual: Bash Variables (BASH_VERSINFO)

More Bash tips echo {01..10} cmd > file 2>&1 export HISTIGNORE='ls*:pwd:cd*' #rsync -av --delete /srv/media/ /mnt/backup/media/ APP_HOST=example.com All Bash tips (52) All topics

Link