Click to See Complete Forum and Search --> : expr confusion FC3
FrankBlourtango
01-22-2005, 06:22 PM
I wanted to start some script programming. Check out the last one trying to multiply. * is mulitiply no? Why the syntax error?
[me@myhost ~]$ expr 24 + 4
28
[me@myhost ~]$ expr 24 - 4
20
[me@myhost ~]$ expr 24 / 4
6
[me@myhost ~]$ expr 24 * 4
expr: syntax error
bs_texas
01-22-2005, 06:32 PM
Found this from a google:
http://howtos.linux.com/guides/abs-guide/moreadv.shtml
expr
All-purpose expression evaluator:
Concatenates and evaluates the arguments according to the operation given (arguments must be separated by spaces).
Operations may be arithmetic, comparison, string, or logical.
expr 3 + 5
returns 8
expr 5 % 3
returns 2
expr 5 \* 3
returns 15
The multiplication operator must be escaped when used in an arithmetic expression with expr.
y=`expr $y + 1`
Increment a variable, with the same effect as let y=y+1 and y=$(($y+1)). This is an example of arithmetic expansion.
z=`expr substr $string $position $length`
Extract substring of $length characters, starting at $position.
FrankBlourtango
01-22-2005, 07:29 PM
Interesting. That does work. Now, why didn't I google that?
Another rung in my long steep climb learning Linux.
Thanks!
bwkaz
01-22-2005, 11:17 PM
For a bit of explanation: The shell interprets wildcards in Unix, not programs (in DOS, for example, programs had to all duplicate the code to interpret wildcards). When you type "*" into the shell, it does pathname expansion, replacing it with the name of each file (except the ones that start with a period) in the current directory. The expr program sees these names between two numbers, and gives you the syntax error.
With the backslash, the shell does not do pathname expansion on the * character.
If you don't want to have to escape it, and if you use bash, then you can use bash's arithmetic expansion instead:
echo $((5*3))
for example, will print 15. bash does the arithmetic, and replaces the expression with the result. However, it only does integer math, and it may not be arbitrary-precision either (it might overflow after the numbers get large).