Linux

bash + 用 bash 進行算術計算

  • February 11, 2018

我需要使用 bash 進行以下操作,優雅的方式是什麼?得到最終的 $sum 值

worker_machine=32
executors_per_node=3

executer=$worker_machine/$executors_per_node-1
spare=$executer X 0.07 
sum=$executer-$spare ( with round the number to down ) 

example:

32/3 = 10 - 1 = 9
9 X 0.7 = 0.6
9 – 0.6 = 8 ( with round the number to down ) 

使用awk, 從 shell 變數中取值:

awk -v n="$worker_machine" -v m="$executors_per_node" \
   'BEGIN { printf("%d\n", 0.93 * (n / m - 1)) }' /dev/null

awk腳本沒有像往常一樣獲得任何輸入,因此我們將其用作輸入文件並在一個塊/dev/null中進行計算和輸出。BEGIN

使用bc

sum=$( printf '0.93 * (%d / %d - 1)\n' "$worker_machine" "$executors_per_node" | bc )
printf '%.0f\n' "$sum"

使用dc

sum=$( printf '%d\n%d\n/\n1\n-\n0.93\n*\np\n' "$worker_machine" "$executors_per_node" | dc )
printf '%.0f\n' "$sum"

引用自:https://unix.stackexchange.com/questions/423412