31

How do you raise m to the power of n? I've searched for this everywhere. What I found was that writing m**n should work, but it doesn't. I'm using #!/bin/sh.

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
Linas
  • 490
  • 1
  • 4
  • 15

6 Answers6

34

I would try the calculator bc. See http://www.basicallytech.com/blog/index.php?/archives/23-command-line-calculations-using-bc.html for more details and examples.

eg.

$ echo '6^6' | bc

Gives 6 to the power 6.

Brian Agnew
  • 254,044
  • 36
  • 316
  • 423
  • Awesome! Used to do my own math functions in bash, created a lot of useless ugly code! Thanks! Didn't know about bc. – Thibault D. Jun 23 '14 at 15:42
30

Using $n**$m really works indeed. Maybe you don't use the correct syntax to evaluate a math expression. Here's how I get the result on Bash:

echo $(($n**$m))

or

echo $[$n**$m]

The square brackets here are not meant to be like the test evaluator in the if statement so you can you use them without spaces too. I personally prefer the former syntax with round brackets.

Gianni
  • 309
  • 3
  • 2
  • 1
    This question asked for a solution for *shell* which means POSIX shell. Your solution does not work in a POSIX compliant shell like dash but just happens to work in more featureful shells like bash or zsh. – josch Jul 22 '17 at 19:21
  • 3
    This is the answer that I was looking for and that I would accept. Thank you @Gianni – Alexx Roche Oct 13 '17 at 09:11
  • 2
    Note that this is limited to integers only - Bash can't handle non-integer arithmetic. Also, `echo $((n ** n))` will work as well - no need for `$` to expand variables inside the arithmetic expression, `(( ... ))`. – codeforester Oct 20 '18 at 19:44
9

using bc is an elegant solution. If you want to do this in bash:

$ n=7
$ m=5

$ for ((i=1, pow=n; i<m; i++)); do ((pow *= n)); done
$ echo $pow
16807

$ echo "$n^$m" | bc  # just to verify the answer
16807
glenn jackman
  • 207,528
  • 33
  • 187
  • 305
4

You might use dc. This

dc -e "2 3 ^ p"

yields

8
unutbu
  • 711,858
  • 148
  • 1,594
  • 1,547
1

My system admin didn't install dc so adding to other correct answers, I bet you have not thought of this -

a=2
b=3
python -c "print ($a**$b)"
>> 8

works in bash/shell.

markroxor
  • 4,217
  • 2
  • 26
  • 38
0
#! /bin/bash
echo "Enter the number to be done"
n=2
read m
let P=( $n**$m )
echo "The answer is $p"

ANSWER

Enter the number to be done
3
The answer is 8 
N3R4ZZuRR0
  • 2,305
  • 3
  • 13
  • 30