问题
How do I save the result of evaluating a mathematical expression to a variable using bash? My code is the following:
W1=$(bpimagelist -U -d 11/01/2013 00:00:00 -e 11/05/2013 00:00:00 -pt FlashBackup-Windows | tail -n +3 | awk '{s+=$5} END {print s/1024/1024/1024}')
W2=$(bpimagelist -U -d 11/01/2013 00:00:00 -e 11/05/2013 00:00:00 -pt MS-Windows | tail -n +3 | awk '{s+=$5} END {print s/1024/1024/1024}')
echo "$W1+$W2" | bc | awk '{printf "%.02f\n", $1}'
Console Output:
96.86
I am looking for a code similar to this:
W="$W1+$W2" | bc | awk '{printf "%.02f\n", $1}' (not correct syntax though)
Any ideas?
回答1:
W3=$( echo $W1+$W2 | bc )
... have you tried this?
回答2:
Two options:
Use back tics:
W1=`command`
Use parens
W1=$(command)
Your command can be as complex as what you have above (e.g. multiple commands joined with pipes)
Option 2 allows for nesting of commands, e.g.
W1=$(command1 $(command2))
回答3:
This would work if both W1
and W2
were integers:
(( W = W1 + W2 ))
It seems you may be dealing with floating point numbers, though, so something like this might work in that case:
W="$(bc <<< "${W1} + ${W2}")"
来源:https://stackoverflow.com/questions/20138516/mathematical-expression-result-assigned-to-a-bash-variable