I tried
开发者_如何学Cecho 10**2
which prints 10**2
. How to calculate the right result, 100?
You can use the let
builtin:
let var=10**2 # sets var to 100.
echo $var # prints 100
or arithmetic expansion:
var=$((10**2)) # sets var to 100.
Arithmetic expansion has the advantage of allowing you to do shell arithmetic and then just use the expression without storing it in a variable:
echo $((10**2)) # prints 100.
For large numbers you might want to use the exponentiation operator of the external command bc
as:
bash:$ echo 2^100 | bc
1267650600228229401496703205376
If you want to store the above result in a variable you can use command substitution either via the $()
syntax:
var=$(echo 2^100 | bc)
or the older backtick syntax:
var=`echo 2^100 | bc`
Note that command substitution is not the same as arithmetic expansion:
$(( )) # arithmetic expansion
$( ) # command substitution
Various ways:
Bash
echo $((10**2))
Awk
awk 'BEGIN{print 10^2}' # POSIX standard
awk 'BEGIN{print 10**2}' # GNU awk extension
bc
echo '10 ^ 2' | bc
dc
dc -e '10 2 ^ p'
Actually var=$((echo 2^100 | bc))
doesn't work - bash is trying to do math inside (())
. But a
command line sequence is there instead so it creates an error
var=$(echo 2^100 | bc)
works as the value is the result of the command line executing inside
()
精彩评论