M HYPE SPLASH
// general

How to check if a directory exists in Linux command line?

By Abigail Rogers

How to check if a directory exists in Linux command line?

Solution: [ -d ¨a¨ ]&&echo ¨exists¨||echo ¨not exists¨

1

7 Answers

$ if test -d /the/dir; then echo "exist"; fi 
5

Assuming your shell is BASH:

if [ -d /the/dir ]; then echo 'Exists'; else echo 'Not found'; fi
2

The canonical way is to use the test(1) utility:

test -d path && echo "Directory Exists"

where path is the pathname of the directory you want to check for.

For example:

test -d Desktop/ && echo "Directory Exists"
Directory Exists
test -d Desktop1/ && echo "Directory Exists"
# nothing appers
3
[ -d /home/bla/ ] && echo "exits"
2

[ -d "YOUR_DIR" ] && echo "is a dir"

e.g.:

[ -d / ] && echo "root dir"

will output: root dir.

2

To check if a directory exists in a shell script you can use the following:

dir=$1
if [ -d "$dir" ]; then #means that $dir exists.
fi

to check the opposite , add ! before the -d ->[ ! -d ....]

1

I usually just ls it:

ls my/directory/

If it exists, you'll see its contents, if it doesn't exist you'll see an error like this:

ls: cannot access 'my/directory': No such file or directory

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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