I have a question about the structure of conditional statements that are to be used at the bash command line.
This question shows:
if [ -z "${VAR}" ]; then echo "VAR is unset or set to the empty string"
Here, the it appears that the then
is only being called when the variable VAR
does not exist. This is confirmed from here.
However, for directories, this question shows:
if [ -d $directory_name ]; then echo "Directory already exists"
Here, it would appear that the then
is only being called when the variable directory_name
does exist. This is confirmed from here (scroll down to -d
).
My problem: I recently tried to check if a variable existed or not. When I tried to apply the same logic to directories, I was surprised that it cannot be done. Here is what I tried:
dir_full_path='/mnt/iso'
if [ -d $dir_full_path ]; then echo 'Directory does not exist'; else echo 'Does exist'; fi
When I ran these 2 lines, the directory path /mnt/iso
did not exist. So I expected the conditional to return Directory does not exist
. Instead, it did the opposite and it returned Does exist
.
Question: This is quite confusing since it seems like the same structure of a conditional cannot be used for a directory and for a variable. Is this true? If so, then is this difference documented somewhere?