0

Why does an empty variable test true if I check for existing directory?

I have two array's with a couple of dirs to process, which I loop / check like this:

for n in {1..20}
do
   if test -d ${dir[$n]}
   then
       echo "Execute ${dir[$n]}"
   fi
   if test -d ${other[$n]}
   then
       echo "Execute ${other[$n]}"
   fi 
done

However, after execution of the existing dirs the script also tries to execute the none existing array elements. It does not matter if I check for dir, file or even nonempty file.
Why?

Of course I can do a separate check if an element exists before checking if the dir exist, but can I not do this in one check?

1 Answer 1

1

Put your ${foo[$n]} in double quotes:

if test -d "${dir[$n]}"

Consider:

$ test -d '' || echo false
false
$ test -d || echo false
$

In general, always put variable dereferences into double quotes. If you don't and a variable is undefined then bad things happen, as you're seeing here.

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

2 Comments

Sometimes life can be so easy :) Thanks!
I'd consider it to be a bug in test: Actually it should output a "syntax error" and exit with some error code different from 1. Doing an strace showed that test did not test anything for test -d.

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.