Get ceiling integer from number in linux (BASH)

后端 未结 13 1975
陌清茗
陌清茗 2020-12-01 04:54

How would I do something like:

ceiling(N/500)

N representing a number.

But in a linux Bash script

13条回答
  •  孤城傲影
    2020-12-01 05:31

    Here's a solution using bc (which should be installed just about everywhere):

    ceiling_divide() {
      ceiling_result=`echo "($1 + $2 - 1)/$2" | bc`
    }
    

    Here's another purely in bash:

    # Call it with two numbers.
    # It has no error checking.
    # It places the result in a global since return() will sometimes truncate at 255.
    
    # Short form from comments (thanks: Jonathan Leffler)
    ceiling_divide() {
      ceiling_result=$((($1+$2-1)/$2))
    }
    
    # Long drawn out form.
    ceiling_divide() {
      # Normal integer divide.
      ceiling_result=$(($1/$2))
      # If there is any remainder...
      if [ $(($1%$2)) -gt 0 ]; then
        # rount up to the next integer
        ceiling_result=$((ceiling_result + 1))
      fi
      # debugging
      # echo $ceiling_result
    }
    

提交回复
热议问题