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¨
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.
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.
fito check the opposite , add ! before the -d ->[ ! -d ....]
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