问题
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