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

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

link|improve this question
1  
So mark it as the solution. – BlueRaja Jan 21 '10 at 17:07
feedback

migrated from stackoverflow.com Jan 21 '10 at 16:16

This question came from our site for professional and enthusiast programmers.

5 Answers

$ if test -d /the/dir; then echo "exist"; fi 
link|improve this answer
I need it in command line, not in a script. – Emanuel Jan 21 '10 at 15:33
2  
That is command line. You can type that into bash directly, or you can resume it to test -d /the/dir: test -d /the/dir && echo "exist" || echo "does not exist" but they are really the same. – David Rodríguez - dribeas Jan 21 '10 at 15:37
feedback
[ -d /home/bla/ ] && echo "exits"
link|improve this answer
Can I have something like ELSE, to show a text even if the directory does´n exists? – Emanuel Jan 21 '10 at 15:40
feedback

Assuming your shell is BASH:

if [ -d /the/dir ]; then echo 'Exists'; else echo 'Not found'; fi
link|improve this answer
syntax error near unexpected token `then' – Emanuel Jan 21 '10 at 15:52
feedback

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

test -d path

where "path" is the pathname of the directory in question.

link|improve this answer
feedback

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

e.g.:

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

echos: root dir.

link|improve this answer
[-d: command not found this is what I get – Emanuel Jan 21 '10 at 15:35
Between "[" and "-" MUST be a space. This should work on Bourne and Bash shell. – dz Jan 21 '10 at 15:38
feedback

Your Answer

 
or
required, but never shown