#!/bin/sh count=0 foo=0 echo "foo $foo" while [ "$foo" -eq 0 ] && [ "$count" -lt 10 ]; echo "inside while: foo $foo" count=$((count+1)) foo=1 done echo "after while"
you'd expect script above output following, right?
foo 0 inside while: foo 0 after while
and on many other machines, own. not mine ...
foo 0 inside while: foo 0 inside while: foo 1 inside while: foo 1 ... (infinite loop)
am doing wrong, or missing obvious?
on (broken?) machine, if tweak while
conditional use "obsolescent" -a
operator, "fixes" problem (whatever is). why?
assuming no hidden characters in script text (an assumption suggest putting effort verifying!), indeed exhibiting behavior contrary posix sh standard.
n1 -eq n2
- true if integers n1 , n2 algebraically equal; otherwise, false.
notably, makes no specifications or guarantees happens if either argument not in fact integer; instance, if would be integer, has carriage return or other nonprinting character on end.
other items try, in order:
- run
sh -x yourscript
, , @ exact arguments calledtest
when running loop. determine whether second test in&&
chain run @ all. - change operator
-eq
=
, running string comparison rather numeric comparison (and thereby ensuring string containing hidden characters fail compare string0
, rather relying on undefined behavior in case). - replace
[ "$foo" -eq 0 ]
false
, , ensure contents of loop not run (thus sanity-checking other core parts of shell's implementation).
Comments
Post a Comment