1

What do the BASH file test operators return when the path argument is an empty string? For example:

directory=""
# Something may or may not set "directory"
if [ -d "$directory" ]; then
    # Do something...
fi
0

2 Answers 2

4

You need to quote $directory:

if [ -d "$directory" ]; then

Otherwise, after expansion you are left with the equivalent of

if [ -d ]; then

which is equivalent to if [ -n "-d" ]; then, and so is always true. (-d is a non-empty string.)

Sign up to request clarification or add additional context in comments.

Comments

0

In your example, the statement will yield the following test:

if [ -d  ]; then
   ...
fi

Which will not test what you wish to.

What is the accepted practice to prevent such error is to encase the variable in double quotes like this:

if [ -d "$directory" ]; then
   ...
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.