bash + bashを使用した算術計算

bash + bashを使用した算術計算

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 ) 

ベストアンサー1

を使用してawkシェル変数から値を取得します。

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"

おすすめ記事