Linux - NewbieThis Linux forum is for members that are new to Linux.
Just starting out and have a question?
If it is not in the man pages or the how-to's this is the place!
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
I am trying to use expr to do simple arithmetic. I read user input (like 2+3) from the keyboard and store it in a variable. When I use expr to perform the calculation it needs me to make a space between the numbers and the operand. Another thing is that when I multiply it gives me an error saying "expr: Syntax error".
Here is my code:
while true
do
echo "Enter Arithmetic Calculation:"
read calc
echo `expr $calc`
done
I offer two alternatives: 1) you can pass the calculation to bc without modifying the input, i.e.
Code:
echo $calc | bc
2) in bash you can try the arithmetic expansion, i.e.
Code:
echo $(($calc))
If you really want to use expr, take in mind that the multiplication operator must be escaped as \*. So you have to parse the input and transform the arithmetic operators to escape them and/or to add blank spaces, but this is a little more tricky and if you really don't need it, I suggest one of the two methods mentioned above.
expr is a little choosy about its parameter, you must space them correctly, and in the case of a * you have to escape it to stop the shell from treating it as a wildcard, which is why you get the syntax error.
If you're using the bash shell try this instead of the expr line.
Code:
echo $[$calc]
edit:
I see others have recommended $(( )) rather than $[ ] and as $(( )) appears to be listed in the manual pages for arithmetic you're probably better off sticking with that. Anyone know where I've picked up $[ ] from? Is it old bourne shell syntax or something?
Also an excerpt from the Advanced Bash Scripting Guide, Example 8.2 Using Arithmetic Operations
Code:
n=$(($n + 1))
echo -n "$n "
: $[ n = $n + 1 ]
# ":" necessary because otherwise Bash attempts
#+ to interpret "$[ n = $n + 1 ]" as a command.
# Works even if "n" was initialized as a string.
echo -n "$n "
n=$[ $n + 1 ]
# Works even if "n" was initialized as a string.
#* Avoid this type of construct, since it is obsolete and nonportable.
# Thanks, Stephane Chazelas.
echo -n "$n "
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.