Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mathematical expression result assigned to a Bash variable

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?

like image 543
user3016638 Avatar asked Dec 02 '25 12:12

user3016638


1 Answers

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}")"
like image 67
twalberg Avatar answered Dec 05 '25 03:12

twalberg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!