Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a directory exists in subdirectory in shell script

What command checks if a directory exists in another path using shell script?

I searched about this, but all I could find was checking if a directory exists in "current" directory.

if [ -d "$DIRECTORY" ]; then
  # found "any" directory
fi

This doesn't satisfy when I want to know if "any" directory exist inside of another directory.

if [ -d "./PATH/$DIRECTORY" ]; then
  # found "any" directory in subdirectory
fi

Apparently this did not work. This still checks from current working directory, not the path I have given.

Any suggestions?

I would like to use this in if condition, so answering with keeping that form would be helpful.

EDIT

In shell script I added as following:

#!/bin/bash

ls -ld ./smth/world/
echo DIRECTORY=$DIRECTORY

if [ -d "./smth/$DIRECTORY/" ]; then
   echo hi
else
   echo nope
fi

in the current directory, I have a directory called "smth". Inside that "smth" I created a dummy directory "world"

EDIT #2

After I added the dot in front of path, I get the following:

drwxrwxr-x 2 (myname) (myname) 4096 Sep  5 14:39 ./smth/world/
DIRECTORY=
found

BUT after I delete the world directory inside of smth directory, still get "found".

like image 323
Humble Thinker Avatar asked Dec 08 '25 04:12

Humble Thinker


1 Answers

That's the other way. ./ if for a directory relative to the current directory, / if for a fully specified directory, i.e.:

If you provide a full path to the directory, you need to remove the dot:

if [ -d "/full/path/to/smth/$DIRECTORY" ]; then
  # found 
fi

If the PATH directory is relative to your current one, the dot must be kept:

if [ -d "./smth/$DIRECTORY" ]; then
  # found
fi

If the DIRECTORY variable is unset, the previous commands will check if there is a directory named PATH in the smth one, if the DIRECTORY variable is set, the test will only succeed if there is a subdirectory with that value under smth.

echo $DIRECTORY will tell you if the DIRECTORY variable is set.

like image 139
jlliagre Avatar answered Dec 10 '25 22:12

jlliagre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!