Reputation: 5913
Assume I have not set the environment variable MY_DIR. Then I do this:
% if [ -d $MY_DIR ]; then
> echo WHAT?
> fi
WHAT?
I don't get it. Why does -d return TRUE if the environment variable doesn't exist?
Upvotes: 1
Views: 57
Reputation: 531683
Without quotes, word-splitting causes the empty string to disappear altogether, and the resulting command is [ -d ]
. A single non-empty argument (]
is ignored for the purpose of counting arguments) makes [
succeed. [ <word> ]
is interpreted as [ -n <word> ]
, which tests that <word>
isn't empty. [ -d ]
is read as [ -n -d ]
and always succeeds since -d
isn't an empty string.
Use quotes.
if [ -d "$MY_DIR" ]; then # when unset, equivalent to [ -d "" ] with two arguments
Upvotes: 2