How can I replace 'bc' tool in my bash script?

一曲冷凌霜 提交于 2020-06-29 13:49:09

问题


I have the following command in my bash script:

printf '\n"runtime": %s' "$(bc -l <<<"($a - $b)")"

I need to run this script on around 100 servers and I have found that on few of them bc is not installed. I am not admin and cannot install bc on missing servers.

In that case, what alternative can i use to perform the same calculation? Please let me know how the new command should look like


回答1:


In case you need a solution which works for floating-point arithmetic you can always fall back to Awk.

awk -v a="$a" -v b="$b" 'BEGIN { printf "\n\"runtime\": %s", a-b }' </dev/null

Putting the code in a BEGIN block and redirecting input from /dev/null is a common workaround for when you want to use Awk but don't have a file of lines to loop over, which is what it's really designed to do.




回答2:


If you are only dealing with integers you can use bash's arithmetic expansion for this:

printf '\n"runtime": %s' $((a - b))

Note that this does assume you have bash available (as you've indicated you do). If you only have a stripped down Bourne shell (/bin/sh) arithmetic expansion is not available to you.



来源:https://stackoverflow.com/questions/48534742/how-can-i-replace-bc-tool-in-my-bash-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!