Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do exponentiation in Bash

Tags:

I tried

echo 10**2 

which prints 10**2. How to calculate the right result, 100?

like image 826
user458553 Avatar asked Oct 08 '10 08:10

user458553


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

How do you power in bash?

To execute a Power Bash, simply hold the action button instead of clicking it once, just like performing a Power Attack with any melee weapon. The Power Bash staggers enemies for a noticeably longer period of time than the regular bash does, in addition to doing more damage.

What does += mean in bash?

The += and -= Operators These operators are used to increment/decrement the value of the left operand with the value specified after the operator. ((i+=1)) let "i+=1"


2 Answers

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 
like image 140
codaddict Avatar answered Sep 28 '22 10:09

codaddict


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' 
like image 44
ghostdog74 Avatar answered Sep 28 '22 11:09

ghostdog74