Comparing numbers in Bash

前端 未结 8 1719
栀梦
栀梦 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
    
    0 讨论(0)
  • 2020-11-22 02:58

    There is also one nice thing some people might not know about:

    echo $(( a < b ? a : b ))
    

    This code will print the smallest number out of a and b

    0 讨论(0)
提交回复
热议问题