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
.
Asked
Active
Viewed 5.7k times
31
![](../../users/profiles/3266847.webp)
Benjamin W.
- 33,075
- 16
- 78
- 86
![](../../users/profiles/1008859.webp)
Linas
- 490
- 1
- 4
- 15
-
2because `m**n` is a bash feature that is not available in sh – phunehehe Jul 08 '18 at 22:47
6 Answers
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.
![](../../users/profiles/12960.webp)
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.
![](../../users/profiles/4556710.webp)
Gianni
- 309
- 3
- 2
-
1This 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
-
3This is the answer that I was looking for and that I would accept. Thank you @Gianni – Alexx Roche Oct 13 '17 at 09:11
-
2Note 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
![](../../users/profiles/7552.webp)
glenn jackman
- 207,528
- 33
- 187
- 305
4
You might use dc. This
dc -e "2 3 ^ p"
yields
8
![](../../users/profiles/668103.webp)
theWayofthecode
- 3
- 2
![](../../users/profiles/190597.webp)
unutbu
- 711,858
- 148
- 1,594
- 1,547
-
this might interest ppl interested in dc https://unix.stackexchange.com/a/124524/30352 – Aquarius Power Jan 05 '19 at 16:17
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.
![](../../users/profiles/4982729.webp)
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
![](../../users/profiles/5073281.webp)
N3R4ZZuRR0
- 2,305
- 3
- 13
- 30