How to assign the output of calculation to a shell

2019-08-06 05:59发布

问题:

I wanted to do this calculation a * 256 ** 3 + b * 256 ** 2 + c * 256 + d and assign output to variable and print dec.

dec ='a * 256 ** 3 + b * 256 ** 2 + c * 256 + d'
echo $dec

I am getting syntax error with the above lines.

回答1:

First of all, assignment is done this way

dec='a * 256 ** 3 + b * 256 ** 2 + c * 256 + d'

This is where your syntax error come from. Then you just have to evaluate your string with the operator $(( )) this way :

echo $((dec))


回答2:

For integer arithmetic, you can use the shell:

dec=$(( a * 256 ** 3 + b * 256 ** 2 + c * 256 + d ))
echo "$dec"

This uses an arithmetic context (( ... )) to calculate the value.

Note that there is no space in an assignment, this is important!

The shell does not support floating point arithmetic, but bc or awk do. For example, using awk (and assuming that you have shell variables $a, $b, $c and $d defined):

awk -v a="$a" -v b="$b" -v c="$c" -v d="$d" 'BEGIN{print a * 256 ** 3 + b * 256 ** 2 + c * 256 + d}'

or using bc:

printf '%s * 256 ^ 3 + %s * 256 ^ 2 + %s * 256 + %s\n' "$a" "$b" "$c" "$d" | bc -l

Using the string format specifier %s for each of the shell variables means that no precision is lost before passing the values to bc.



标签: shell