I want to perform a test: if a certain variable exists, is non-empty, and its value matches an existing directory, then "exists" should be outputted.

I did the following:

$ echo $var

$ if [ -d $var ]; then echo "exists"; fi

I got "exist", although I did not assign any value to $var. Why did this happen, and how do I test this properly?


  • If @WillW answered your question, please mark it as accepted! :)
    – Swivel
    Jun 4 '19 at 14:42

I think you need to wrap $var in quotes.

if [ -d "$var" ]; then echo "exists"; fi


[ -d FILE ] True if FILE exists and is a directory

You probably want to use one of these tests instead:

[ -z STRING ] True of the length if "STRING" is zero.

[ -n STRING ] or [ STRING ] True if the length of "STRING" is non-zero.

From https://www.tldp.org/LDP/abs/html/fto.html

how do I test this properly? if a certain variable exists, is non-empty

This question is discussed in detail https://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash here.

its value matches an existing directory

This code [[ "${F1AR[@]}" =~ "${NAME##*/}" ]] checks if values match existing directories. From https://github.com/BuildAPKs/buildAPKs/blob/master/scripts/bash/build/build.github.bash#L59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.