Comparing numbers in Bash

前端 未结 8 1723
栀梦
栀梦 2020-11-22 02:03

I\'m starting to learn about writing scripts for the bash terminal, but I can\'t work out how to get the comparisons to work properly. The script I\'m using is:



        
8条回答
  •  长情又很酷
    2020-11-22 02:56

    I solved this by using a small function to convert version strings to plain integer values that can be compared:

    function versionToInt() {
      local IFS=.
      parts=($1)
      let val=1000000*parts[0]+1000*parts[1]+parts[2]
      echo $val
    }
    

    This makes two important assumptions:

    1. Input is a "normal SemVer string"
    2. Each part is between 0-999

    For example

    versionToInt 12.34.56  # --> 12034056
    versionToInt 1.2.3     # -->  1002003
    

    Example testing whether npm command meets minimum requirement ...

    NPM_ACTUAL=$(versionToInt $(npm --version))  # Capture npm version
    NPM_REQUIRED=$(versionToInt 4.3.0)           # Desired version
    if [ $NPM_ACTUAL \< $NPM_REQUIRED ]; then
      echo "Please update to npm@latest"
      exit 1
    fi
    

提交回复
热议问题