How to do exponentiation in Bash
Solution 1
You can use the let
builtin:
let var=10**2 # sets var to 100.
echo $var # prints 100
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
Solution 2
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'
Solution 3
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
()
user458553
Updated on December 16, 2021Comments
-
user458553 over 2 years
I tried
echo 10**2
which prints
10**2
. How to calculate the right result, 100? -
DarkDust over 13 yearsInstead of
$(( ... ))
it's also possible to use$[ ... ]
. I find the later visually more appealing but that's just my taste. Don't know if there are any differences between the two, though. It seems they behave the same. -
slezica over 13 yearsAlberto: all this parenthesis, lets and $ are needed because bash, being a simple command-line interpreter, does better assuming everything is a string and should be treated as such, unless explicitly indicated otherwise. Saludos!
-
wisbucky almost 5 years@DarkDust
$[...]
is an older deprecated syntax. unix.stackexchange.com/questions/209833/… -
bballdave025 almost 4 yearsThis is very helpful You should put it as a comment to the answer above.
-
bballdave025 almost 4 yearsGood catch, by the way; the other, accepted commands followed the
$((...))
pattern (Double Parentheses Construct, source Advanced Bash-Scripting Guide, "permits arithmetic expansion and evaluation"). Here, as you've noted, we need Command Substitution, i.e. the$(...)
construct. The ABS guide notes, "The$(...)
has superceded backticks". The Bash Beginners Guide, section 3.4.5-6, has both described right next to each other. -
Wrichik Basu almost 3 years
-
Nathaniel M. Beaver almost 3 years@WrichikBasu I submitted an edit; it's fixed now.