Mathematical expression result assigned to a Bash variable

陌路散爱 提交于 2021-02-05 07:57:45

问题


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:

  1. Use back tics:

    W1=`command`

  2. 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

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