Page 1 of 1

verify EXPR bug in SHELL

Posted: Thu Nov 09, 2017 1:21 pm
by paulwratt
can a few people verify a bug in different versions of Raspbian, on a console:

Code: Select all

expr 85 * 3
I dont use X, Bash is the $SHELL

I just verified this works:

Code: Select all

expr 85 \* 3
Cheers

Paul

Re: verify EXPR bug in SHELL

Posted: Thu Nov 09, 2017 1:28 pm
by jahboater
Try doing

echo *

You will see that the shell expands * into all the visible filenames in the current directory.
\* stops that expansion.

There is no bug.

Re: verify EXPR bug in SHELL

Posted: Thu Nov 09, 2017 1:29 pm
by n67
This has nothing to do with BASH (other than that is common behavior in all Unix shells) or the Pi. It is a basic limitation of 'expr'. As you've deduced, you need to escape any arguments to 'expr' that are "special" to the shell. This includes, as you've noted, the * character.

'expr' is pretty much obsolete in the modern world. Back in the day, it was all we had, but there are better tools available now.

Using bash, the simplest way to do math in the shell is to use $(()) like this:

$ echo $((85*3))
255
$ foo=85;bar=3
$ echo $((foo*bar))
255
$

Now, if you are maintaining old code that uses 'expr', then the original authors would have been aware of these limitations and coded accordingly. If you are writing new code, don't use 'expr'.

Re: verify EXPR bug in SHELL

Posted: Thu Nov 09, 2017 1:30 pm
by DougieLawson
If you want to do complex maths in bash pipe it into bc with suitable use of apostropes and/or quotes.

Re: verify EXPR bug in SHELL

Posted: Thu Nov 09, 2017 2:50 pm
by piglet
DougieLawson wrote:
Thu Nov 09, 2017 1:30 pm
If you want to do complex maths in bash pipe it into bc with suitable use of apostropes and/or quotes.
Yup: echo '(85 * 3)^2'| bc
65025