17

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?

Isuru
  • 281
  • Related: http://unix.stackexchange.com/questions/40786/how-can-i-do-command-line-integer-float-calculations-in-bash-or-any-language – Bernhard Aug 08 '12 at 05:58

3 Answers3

47

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))
Ulrich Dangel
  • 25,369
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).

jasonwryan
  • 73,126
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)
Premraj
  • 2,542