Wednesday, February 2, 2022

[SOLVED] Check if a directory contains another directory

Issue

How do I check if a given directory contains another directory in shell. I want to pass 2 full path directories. (I know this is stupid, but just for learning purposes). Then I want to see if any one of those 2 paths is contained in the other one.

parent=$1
child=$2

if [ -d $child ]; then
    echo "YES"
else
    echo "NO"
fi

this however makes no use of the parent directory. Only checks if the child exists.


Solution

You can use find to see if one name is contained within another:

result=$(find "$parent" -type d -name "$child")
if [[ -n $result ]]
then echo YES
else echo NO
fi


Answered By - Barmar
Answer Checked By - Cary Denson (WPSolving Admin)