-   Linux - Newbie (
-   -   bash shell math (

jwildeILL 04-25-2017 05:41 PM

bash shell math
I think I am using expr wrong. I need to raise a number to the power of x.

I tried:

expr 3^5
expr 3'^'5

And they don't work

hydrurga 04-25-2017 06:11 PM

Hi jwildeILL.

I see that you have already marked this thread as "Solved".

What was your solution?

jwildeILL 04-25-2017 06:15 PM


Originally Posted by hydrurga (Post 5702145)
Hi jwildeILL.

I see that you have already marked this thread as "Solved".

What was your solution?

echo '(3^5)' | bc

I think expr can only handle basic math like + - * and %

astrogeek 04-25-2017 06:21 PM

Welcome to LQ!

I do not think expr supports the bitwise-or operator, '^' (that is not exponent in the shell). See man expr to verify that.

expr is designed to be used inside command substitution and returns the value of the expression on exit.

Additionally, I do not think expr supports exponents, and you need to protect the * from the shell, so you would need to do something like this...


X=$(expr 3 \* 3 \* 3 \* 3 \* 3)
echo "$X"

From the book Classis Shell Scripting:


# Classic Shell Scripting - Oreilly, Section 7.6.3
# The expr command is one of the few Unix commands that is poorly designed and hard to use.
# Although standardized by POSIX, its use in new programs is strongly discouraged, since
# there are other programs and facilities that do a better job. In shell scripting, the major
# use of expr is for shell arithmetic, so that is what we focus on here. Read the expr(1)
# manpage if you're curious about the rest of what it can do.
# expr's syntax is picky: operands and operators must each be separate command-line arguments;
# thus liberal use of whitespace is highly recommended. Many of expr's operators are also
# shell metacharacters, so careful quoting is also required.

So, let's avoid using it unless you have some special reason to do so - there are better ways!

Your second method is much better, but it does not use the bash power operator (**), and it throws away the result without using it.

You need to use it to set some variable value, or better use it in command substitution context as well. Either of these will work:


echo "$X"

echo "$X"

The first sets the value of the variable X, which you can then use as desired.

The second returns the value which is then placed into the variable X, which you may then use. Alternatively you could simply echo the returned value.

See the bash man page - it is long but very complete and helpful!

Good luck!

jwildeILL 04-25-2017 06:36 PM

Thanks astrogeek for the examples. +1

All times are GMT -5. The time now is 04:06 PM.