Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a directory exists within a given path

I'm creating a simple script for backing up and I want to check if a directory exists in a given path like so:

fullPath=/usr/local/webapps/mydir

if mydir exists in my $fullPath

    then back it up
    else give error
fi

My question is how do I formulate the if statement to check if the last directory exists in the $fullPath variable? Just to clarify, for this case it would be mydir if I used /usr/local it would be local etc.

Thanks in advance!

like image 724
Mantas Avatar asked Aug 21 '12 09:08

Mantas


People also ask

How do you check if a folder exists and if not create it?

You can use os. path. exists('<folder_path>') to check folder exists or not.

How do you check if a file exists in a folder Python?

os. path. exists() to check if a file or directory exists using Python. We further use this method to check if a particular file path refers to an already open descriptor or not.


1 Answers

Duplicate question? Check if a directory exists in a shell script

if [ -d "$DIRECTORY" ]; then
    # Control will enter here if $DIRECTORY exists.
fi

The $DIRECTORY is the pathname

For your case, you can just do:

if [ -d "$fullPath" ]; then
    then back it up
    else give error
fi
like image 86
ronalchn Avatar answered Oct 21 '22 17:10

ronalchn