James Dean
James Dean

Reputation: 165

Match the macOS version number only by major and minor version number

Trying to deal with a result of 10.12.3 - how would I code this when the OS has an optional third numeric value to consider? And, of course, this changes often, so I don't want to look for extended updates. Just the main OS 10.12, 10.11, 10.10, etc.

   if [ "$osv" = "10.12" ]; 
    then
        appi="Applications:App Store.app:Contents:Resources:AppIcon.icns"
    elif [ "$osv" = "10.11" ]; 
    then
        appi="Applications:App Store.app:Contents:Resources:appStore.icns"
    else
        exit
    fi

thanks.

Upvotes: 1

Views: 443

Answers (2)

mklement0
mklement0

Reputation: 437478

Use =~, Bash's regex-matching operator, inside [[ ... ]]:

if [[ $osv =~ ^10\.12(\.?|$) ]]; # ...

This matches both 10.12 and 10.12.3, for instance.

With some duplication you can also use glob-style patterns in a case statement, which may be the best choice in your case:

osv=$(sw_vers -productVersion) # yields, e.g., '10.12' or '10.12.3'
case $osv in
  10.12|10.12.*)
    appi="Applications:App Store.app:Contents:Resources:AppIcon.icns"
    ;;
  10.11|10.11.*)
    appi="Applications:App Store.app:Contents:Resources:appStore.icns"
    ;;
  *)
    exit
esac

Note:

  • Patterns (as also used in globbing) are:

    • conceptually simpler, but much less powerful than regexes (regular expressions).

    • can be used for string matching on the RHS of == inside [[ ... ]] as well as in case statements (see above; inside case, their use is even POSIX-compliant).

  • By contrast, regexes can only be used for string matching inside [[ ... ]] with the =~ operator.

Upvotes: 2

ewcz
ewcz

Reputation: 13087

you could take your variable $osv, keep only the first two fields (assuming that fields are delimited with .), and use the result in the if/else statement(s):

v=$(echo "$osv" | awk -F. 'BEGIN{OFS="."}{print $1,$2}')

so if $osv is 10.12.3, v will be 10.12. In case $osv is merely 10.12, v will be equal to this value as well.

Upvotes: 1

Related Questions