Skip to content

Instantly share code, notes, and snippets.

@scriptingosx
Last active April 15, 2023 10:04
Show Gist options
  • Star 21 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save scriptingosx/670991d7ec2661605f4e3a40da0e37aa to your computer and use it in GitHub Desktop.
Save scriptingosx/670991d7ec2661605f4e3a40da0e37aa to your computer and use it in GitHub Desktop.
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"
@jonmannn
Copy link

jonmannn commented Mar 5, 2018

Looking at this piece:

os_ver=${1-:$(sw_vers -productVersion)}

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

I needed to take into account the leading colon in os_ver. To do that I modified my if statement to this

`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`

@burkestar
Copy link

I think it should have been:

os_ver=${1:-$(sw_vers -productVersion)}

(swap -: with :- to set the default)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment