1

I find this behaviour counter-intuitive:

v=0; ((v)) && echo K; v=1; ((v)) && echo J

echoes:

J

but generally 0 is success:

f() { return 0; }; if f; then echo W; fi

Explain the reasoning?


man page for (( )) says:

If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1.


How best to check if a variable is zero using Arithmetic Evaluation?

4

2 に答える 2

4

The canonical way to test for 0 is [ $something -eq 0 ], often written as [ x$something = x0 ]. (Using = is a string comparison but it is still valid syntax when the variable isn't set or is otherwise blank.) See man expr.

So,

q=0
if [ $q -eq 0 ]; then # or [ x$q = x0 ]
  echo yes, zero
fi

The ((expr)) syntax is a shortcut for the let command, and that command is simply defined to return true status when the expression is non-zero and false otherwise.

And neither ((...)) nor let ... are Posix commands, so some amount of WTF?! may be expected. It's just something the authors of bash either thought up or pulled in from some now-obscure earlier shell. (It seems to be in zsh.) It is not in ash(1), aka dash(1), which is kind of the reference pure-Posix shell.

于 2013-03-24T23:11:47.870 に答える
3

One good reason to "flip" the meaning to 0 sucess any value not 0 not sucess is that you might want to indicate different error conditions.

Using 0 as failure this wouldn't be possible at all as any value != 0 would have been wasted to indicate sucess.

Given a numeric variable the best way to check if the value is 0 is to do exactly that:

((v==0))
于 2013-03-24T23:16:28.403 に答える