Another excerpt from the book “Moving to zsh.” I found this one so useful, I thought I’d like to share it.
You can get the version of zsh with the ZSH_VERSION
variable:
% echo $ZSH_VERSION
5.7.1
And you can get the version of macOS with the sw_vers
command:
% sw_vers -productVersion
10.15.1
Comparing version strings is usually fraught with potential errors. Strings are compared by the character code for each character.‘2
’ is alphabetically greater than ‘10
’ when compared as strings, because the character code for 2
is greater than the character code for 1
. So, a string comparison of macOS version numbers will return that 10.9.5
is greater than 10.15.1
.
Zsh, however, provides a function is-at-least
which helps with version string comparisons.
With a single argument, is-at-least
will return if the current zsh version matches or is higher than a given number:
if ! is-at-least 2.6-17; then
echo "is-at-least is not available"
fi
When you provide two arguments to is-at-least
, then the second argument is compared (using version string rules) with the first and needs to match or be higher:
autoload is-at-least
if is-at-least 10.9 $(sw_vers -productVersion); then
echo "can run Catalina installer"
else
echo "cannot run Catalina installer"
fi
Note: when used in a script, you will probably have to
autoload is-at-least
before using it. In an interactive shell, it is often already loaded, because many other autoloader functions will have already loaded it.