-2

When I try following statements, it doesn't assign values properly to variables and loop goes infinite-

while ( [ $nos -ne 0 ] )
do
    rem = `expr $nos % 10`
    sum = `expr $sum + $rem`
    nos = `expr $nos / 10`
done

But when I remove spaces from left and right side of assignment operator, it works fine. Like this -

while ( [ $nos -ne 0 ] )
do
    rem=`expr $nos % 10`
    sum=`expr $sum + $rem`
    nos=`expr $nos / 10`
done

Why the Shell behaviour is like that?

user286009
  • 7
  • 1
  • 1
  • 4
  • As an aside, `expr` is a Bourneism, present only for backwards compatibility with 1970s-era shells; since literally the early 90s, the POSIX-standardized syntax for math has been `rem=$(( nos % 10 ))`, with only occasional holdouts (Sun being the most notorious) shipping noncompliant `/bin/sh` implementations. – Charles Duffy Jul 04 '16 at 15:10
  • ...you've also got some (lack-of-)quoting-related bugs; http://shellcheck.net/ will find those automatically. – Charles Duffy Jul 04 '16 at 15:12

2 Answers2

0
rem = `expr $nos % 10`

Runs a command rem with its first argument =.

If it weren't for the POSIX sh standard requiring that assignments parse as a single word (which it does), one couldn't pass = as a first argument to a command or function; hence, the standard being written as it is.


There's further expressive power based on whitespace in assignments as well. For instance:

rem= foo

...runs foo with the environment variable rem set to an empty string only for the duration of that single command's execution, just as

var=val foo

sets var to val while running foo. This is useful syntax; if var=val foo were equivalent to var="val foo", it would not be possible.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
-3

In Shell script, you can create function. And to call a function, you just write

function arg1 arg2 ...

That's why, in my opinion, it works like this.

Plus, if you are using bash, you can do $((nos%10)) instead of calling the built-in expr

Krati
  • 1
  • I don't think there is any relation in function call and variable assignment. Please can you elaborate – user286009 Jul 04 '16 at 15:08
  • just watch the other comment then. The space is used as argument separator. So you try to call a function in your first exemple – Krati Jul 04 '16 at 15:11
  • `$(( nos % 10 ))` isn't just bash -- that's part of baseline POSIX. You might be thinking `(( ))`, without the leading `$`, as a math context; *that* part is a bash extension (or, rather, a ksh extension adopted by bash). – Charles Duffy Jul 04 '16 at 15:14
  • Nope, it is just that I dunno about POSIX since i've been only using bash. – Krati Jul 04 '16 at 15:15