Here is the code,
x=
if [ -d $x ]; then
echo "it's a dir"
else
echo "not a dir"
fi
The above code gives me "it's a dir", why? $x is empty, isn’t it?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
is equivalent to:
A simpler way to demonstrate what’s going on is:
which prints
0, indicating that the test succeeded ([is actually a command, equivalent totestexcept that it takes a terminating]argument.)But this:
does the same thing. Does that mean that the missing argument is both a directory and a plain file?
No, it means that it’s not doing those tests.
According to the POSIX specification for the
testcommand, its behavior depends on the number of arguments it receives.With 0 arguments, it exits with a status of 1, indicating failure.
With 1 argument, it exits with a status of 0 (success) if the argument is not empty, or 1 (success) if the argument is empty.
With 2 arguments, the result depends on the first argument, which can be either
!(which reverses the behavior for 1 arguments), or a “unary primary” like-for-d, or something else; if it’s something else, the results are unspecified.(POSIX also specifies the behavior for more than 2 arguments, but that’s not relevant to this question.)
So this:
prints “yes”, not because the missing argument is a directory, but because the single argument
-dis not the empty string.Incidentally, the GNU Coreutils manual doesn’t mention this.
So don’t do that. If you want to test whether
$xis a directory, enclose it in double quotes: