1

I made a small mistake today when writing a bash script. The following code

#!/bin/bash

if [ -n "${UNDEFINED_VAR}"]; then
   echo 'string not empty'
   echo "$UNDEFINED_VAR"
else
   echo 'string empty'
fi

returns string not empty and a blank line. If you look closely I'm missing a space before ] in the upper code. What suprised me a bit was that bash happily runs my code without any unexpected token (or other) syntax errors. On a side note [[ gives a proper syntax error in the upper case.

My question: Is that just undefined behavior since I'm not using legal syntax and bash is free to do anything, or is it some kind of very strange legal syntax giving a very unexpected result?

1

With UNDEFINED_VAR being unset, the command

[ -n "${UNDEFINED_VAR}"]

will expand to

[ -n ]

This is well defined and will be true as the string -n is non-empty.

The default test that [ will perform for a single argument (disregarding ]) is to test for a non-empty string. The string -n is a non-empty string.

| improve this answer | |
  • Thx, perfect answer. Also answers the second question as if [[ -n ]]; then seem not to be legal syntax due to the missing operand after -n (contrary to [ behavior). – Max1 Apr 25 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.