13

I have the following:

versionNumber=$(sw_vers -productVersion) # Finds version number

versionShort=${versionNumber:0:4}  # Cut string to 1 decimal place for calculation

which works when versions are like this:

10.9.2
10.9.5

but it will not match

10.10.3

as it will return only

10.1

but I want the versionShort to be set to

10.10

I am wanting to match the major version, the first dot and the minor version as above.

4

4 回答 4

15

Regexpless solution - cut off last dot and whatever follows it:

versionShort=${versionNumber%.*}
于 2014-06-20T02:09:11.603 回答
13

我有一个类似的问题,但我需要访问所有 3 个部分。我做了一些研究和测试,我发现这很好用

product_version=$(sw_vers -productVersion)
semver=( ${product_version//./ } )
major="${semver[0]}"
minor="${semver[1]}"
patch="${semver[2]}"
echo "${major}.${minor}.${patch}"

要直接回答这个问题,你可以

product_version=$(sw_vers -productVersion)
semver=( ${product_version//./ } )
major="${semver[0]}"
minor="${semver[1]}"
patch="${semver[2]}"
versionShort="${major}.${minor}"

或者你可以使用更少的变量

product_version=$(sw_vers -productVersion)
semver=( ${product_version//./ } )
versionShort="${semver[0]}.${semver[1]}"
于 2016-03-09T21:40:39.167 回答
11

正则表达式解决方案:

[[ $versionNumber =~ ^[0-9]+\.[0-9]+ ]] && echo "${BASH_REMATCH[0]}"

它总是会打印前两个数字,例如所有这些:

10.5
10.5.9
10.5.8.2

将导致10.5输出。您还可以添加一个else子句来检查是否发生了错误(未找到匹配项)。

这是一个更长的版本:

if [[ $versionNumber =~ ^[0-9]+\.[0-9]+ ]]; then
    versionShort=${BASH_REMATCH[0]}
else
    echo "Something is wrong with your version" >&2
fi
于 2014-06-20T03:11:06.447 回答
7

https://github.com/fsaintjacques/semver-tool https://github.com/fsaintjacques/semver-tool/blob/master/src/semver

SEMVER_REGEX="^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(\\-[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?(\\+[0-9A-Za-z-]+(\\.[0-9A-Za-z-]+)*)?$"


function validate-version {
  local version=$1
  if [[ "$version" =~ $SEMVER_REGEX ]]; then
    # if a second argument is passed, store the result in var named by $2
    if [ "$#" -eq "2" ]; then
      local major=${BASH_REMATCH[1]}
      local minor=${BASH_REMATCH[2]}
      local patch=${BASH_REMATCH[3]}
      local prere=${BASH_REMATCH[4]}
      local build=${BASH_REMATCH[5]}
      eval "$2=(\"$major\" \"$minor\" \"$patch\" \"$prere\" \"$build\")"
    else
      echo "$version"
    fi
  else
    error "version $version does not match the semver scheme 'X.Y.Z(-PRERELEASE)(+BUILD)'. See help for more information."
  fi
}

于 2018-05-25T12:49:02.317 回答