Here's a smaller test case for your problem:
output=""
if test [-n] $output
then
echo "Why does this happen?"
fi
This happens because when $output
is empty or whitespace, it expands to nothing, and you just run test [-n]
.
test foo
is true when foo
is non-empty. It doesn't matter that your foo
is a flag wrapped in square brackets.
The correct way to do this is without the brackets, and with quotes:
if test -n "$output"
then
...
fi
As for why $OUTPUT
is a single space, that's simple: it isn't. echo
just writes out its arguments separated as spaces, and you specified multiple arguments. The correct code is echo "output is '$OUTPUT'"