Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Sample bash script to show how to parse the macOS version
#!/bin/bash
# use argument 1 as the version or get it from sw_vers
os_ver=${1-:$(sw_vers -productVersion)}
# string comparison
if [[ "$os_ver" == 10.13.* ]]; then
echo "macOS High Sierra"
elif [[ "$os_ver" == 10.12.* ]]; then
echo "macOS Sierra"
else
echo "(Mac) OS X something"
fi
# regular expression
if [[ "$os_ver" =~ 10.1[23].* ]]; then
echo "It's one of the Sierras"
fi
# awk
echo "minor version with awk: " $(echo "$os_ver" | awk -F. '{ print $2; }')
echo "patch version with awk: " $(echo "$os_ver" | awk -F. '{ print $3; }')
# array
IFS='.' read -r -a ver <<< "$os_ver"
echo "minor version with array: ${ver[1]}"
echo "patch version with array: ${ver[2]}"
# numerical comparison
if [[ "${ver[1]}" -ge 9 ]]; then
echo "somewhere in California"
elif [[ "${ver[1]}" -ge 2 ]]; then
echo "officially a feline"
else
echo "secretly a feline"
fi
# get the build number:
build_ver=${2-:$(sw_vers -buildVersion)}
if [[ "${ver[1]}" -le 5 ]]; then
build_number="${build_ver:3}"
else
build_number="${build_ver:4}"
fi
if [[ ${build_number: -1} == 'a' ]]; then
build_number="${build_number:0:$((${#build_number}-1))}"
fi
echo "build number: $build_number"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment