0

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
exists

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

screenshot

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

2 Answers 2

3

I think you need to wrap $var in quotes.

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

0

[ -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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .