Bash – Simple Shell Script with Arithmetic issue… ** is giving me trouble

bashshellshell-script

When I run this script I get this error:

./myscript.sh: 16: arithmetic expression: expecting primary: "1 ** 1"

When I run this shell script with bash, as in #! /bin/bash on the first line, the math works properly; unfortunately I need to use /bin/sh. What am I doing wrong? I'm on Linux Mint if that matters.

#! /bin/sh

x=1
while [ $x -le 10 ]
do
    y=1
    while [ $y -le 10 ]
    do
        echo $(($y ** $x))"   \c"
        y=`expr $y \+ 1`
    done
    echo
    x=`expr $x \+ 1`
done

Best Answer

Standard shell arithmetic only allows integer arithmetic operations. This doesn't include ** for exponentiation, which bash has as an extension.

Integer exponentiation is easy enough to implement as a shell function (though you'll run into wraparound soon).

pow () {
    set $1 $2 1
    while [ $2 -gt 0 ]; do
      set $1 $(($2-1)) $(($1*$3))
    done
    echo $3
}

As an aside, why use expr here? Shell arithmetic can do addition.

Related Question