14

I'm learning Shell scripting for a diploma in IT I'm currently doing. I'm trying to write a small script that adds two numbers as shown as in one of the tutorials we were given.

echo "Enter two numbers"
read num1 num2
sum = 'expr $num1 + $num2'
echo "The sum is = $sum"

However when I give it the execution permission and run the script, it gives me this error.

sum: =. No such file or directory.
sum: expr $num1 + $num2: No such file or directory

enter image description here

I tried running this on both Ubuntu and Fedora but same error occurs. Can anyone please tell me what I'm missing here?

42

First you have to get rid of the spaces for the assignment, e.g

sum='expr $num1 + $num2'

then you have to change ' to a ` or even better to $():

sum=$(expr "$num1" + "$num2")

instead of using expr you can also do the calculation directly in your shell:

sum=$((num1 + num2))
| improve this answer | |
  • 3
    If the motivation for using expr instead of $((...)) is a desire to be portable to classic Bourne shell, then it's a good idea to avoid $(...) as well. – Alan Curry Aug 8 '12 at 4:55
  • 2
    @AlanCurry are there any shells not supporting $()? As far as i know it is required by posix, e.g. all posix compatible shells should support $() – Ulrich Dangel Aug 8 '12 at 5:27
  • 1
    @UlrichDangel The original Bourne shell didn't have $(…), but it has about died out (maybe someone somewhere is still running /bin/sh on Solaris). – Gilles 'SO- stop being evil' Aug 8 '12 at 22:33
  • The C Shell doesn’t support $(…) –– or at least, not all versions. – Scott Jan 11 '13 at 22:32
  • What is the purpose of having double quotes around the variables? – kojow7 Apr 3 '18 at 23:06
9

You have probably misread backticks as single quotes in the line:

sum = 'expr $num1 + $num2'

See Greg's Wiki on using $(...) instead.

This works as expected:

sum=$(expr "$num1" + "$num2")

Also note there are no gaps around the equals sign (the variable assignment).

| improve this answer | |
1

expr is an external program used by Bourne shell(i.e. sh). Bourne shell didn't originally have any mechanism to perform simple arithmetic. It uses expr external program with the help of backtick.

The backtick(`) is actually called command substitution . Command substitution is the mechanism by which the shell performs a given set of commands and then substitutes their output in the place of the commands.

sum=`expr $num1 + $num2`

In bash(bourne again shell) it has the following systax, it won't use extrnal program expr.

sum=$((num1+num2))

if we want to use the external program expr. we have the following systax:

sum=$(expr $num1 + $num2)
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.