Bash – Why does while [ 0 ] go into infinite loop

bashshelltest

I see the same behaviour for below loop as the loop with while [ 1 ]. Why is that so?

while [ 0 ]; do
    echo "hello"
done

Best Answer

Single square brackets in the shell is a synonym for test (either the separate command or the shell built-in), so [ 0 ] means the same thing as test 0. test is for doing comparisons and testing the attributes of files, as you can read about in its manpage. When it isn't given an expression that looks like a comparison, file test, or one of the other operations it can do, it will instead test if the argument is present and a non-empty string. Neither 0 or 1 are really appropriate inputs for test, and as non-empty strings test simply succeeds and your while loop loops forever.

You may want to try instead

while false; do
  echo "hello"
done

possibly replacing false with true. Or maybe what you want is to use (( )):

while (( 0 )); do
  echo "hello"
done

Which will behave like most languages, where 0 means failure/false and 1 means success/true.

Related Question