2

I am doing add operation as

#!/bin/sh
a=10
b=20
c='expr $a + $b'
echo "$c"
echo "$a"
echo "$b"

but it is showing output as

expr $a + $b
10
20

what is wrong with expr

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
user183924
  • 21
  • 2

1 Answers1

7

Your example uses the wrong type of quotes:

a=10 b=20 c='expr $a + $b' echo "$c" echo "$a" echo "$b"

which should be (as a start):

a=10
b=20
c=`expr $a + $b`
echo "$c"
echo "$a"
echo "$b"

but more readable:

a=10
b=20
c=$(expr $a + $b)
echo "$c"
echo "$a"
echo "$b"

If you want to put all of those statements on a single line, separate them by semicolons:

a=10; b=20; c=$(expr $a + $b); echo "$c"; echo "$a"; echo "$b"
Thomas Dickey
  • 75,040
  • 9
  • 171
  • 268
  • 1
    FYI the original wasn't on one line, but it wasn't formatted properly so the site wrapped it all up.... – Stephen Harris Aug 09 '16 at 23:58
  • Thanks very much !! it works as c=$(expr $a + $b), but wondering why all study material use c='expr $a + $b ? – user183924 Aug 10 '16 at 00:02
  • 4
    Some programs (un)helpfully translate quotes. In Microsoft Word, the feature is called smart quotes. – Thomas Dickey Aug 10 '16 at 00:06
  • 2
    @user183924 those are supposed to be back ticks, like the character under the ~ on most keyboards, but sure look a lot like single quotes, so if you don't know what to look for even if something else doesn't "helpfully" translate them our eyes often will, which is part of the reason for the `$()` syntax Thomas showed here – Eric Renouf Aug 10 '16 at 00:49
  • aah ok.. Thanks very much for detailed feedback.. – user183924 Aug 10 '16 at 02:28