Reputation: 165
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?
Upvotes: 0
Views: 797
Reputation: 1919
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.
Upvotes: 1