Bash Version Detection – How to Detect Bash >=4.0

bashversion

I am writing a script that uses read -i, so it requires Bash 4.0 or newer.

Unfortunately, as of early 2020, macOS still ships with Bash 3.x, and many users of my script will be using Macs. Since Apple has changed the default shell to zsh, I have no hope that they'll update the bundled version.

As such, I want my script to detect whether Bash is new enough and exit with a helpful error message that directs the user to upgrade.

I know I can compare ${BASH_VERSION}, but that's a string with a non-numeric, potentially unreliable format. It feels fragile to make assumptions about it.

What's the best way to accomplish this?

requireBash4() {
  if <something here>; then
    >&2 echo "Bash 4.0 or newer is required."
    >&2 echo "Once you're upgraded, re-run this script."
    exit 1
  fi
}

Best Answer

if ((BASH_VERSINFO >= 4)); then ...

Notice that BASH_VERSINFO is an array. As with any array in bash, using it as a plain variable refers to its 0-th element. You can also use ((BASH_VERSINFO[0] >= 4)) if you find it more clear.

And yes, this variable and syntax are supported since at least bash 2.0.

BASH_VERSINFO

A readonly array variable whose members hold version information for this instance of bash. The values assigned to the array members are as follows:

BASH_VERSINFO[0] The major version number (the release).
BASH_VERSINFO[1] The minor version number (the version).
BASH_VERSINFO[2] The patch level.
BASH_VERSINFO[3] The build version.
BASH_VERSINFO[4] The release status (e.g., beta1).
BASH_VERSINFO[5] The value of MACHTYPE.

Related Question