Search code examples
bash

Why "test <blah>" expression in bash is true?


I have fairly often seen that test <blah> expression is used in examples for endless while-loops. For example while [ 1 ]; do echo "will loop endlessly"; done. [ 1 ] is same as test 1 which will always be true:

$ test 1
$ echo $?
0
$ 

However, expression does not need to be an integer, but can also be a word, e.g. test [ blah ]. Why are test [ 1 ] or test [ blah ] true, i.e. expression does not go through any actual tests, does it?


Solution

  • It's synoymous to using -n which tests if a string is empty or not:

    test -n "$x"
    

    And 1 and blah are non-empty strings so they give true expressions.

    But it's not recommended at least when testing variables since a variable can contain an operator that's valid to test and results may go unexpected. Prefer using -n instead.

    And as suggested by @Keith Thompson, if creating an infinite loop is intended, better just use while true or while : as it's more clearly written and also skips unnecessary testing of expressions.

    For bash, for (( ;; )); do may come more efficient as it doesn't call another builtin and doesn't keep testing $?.