Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

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

share|improve this question

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

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

4  
So mark it as the solution. –  BlueRaja Jan 21 '10 at 17:07

5 Answers 5

$ if test -d /the/dir; then echo "exist"; fi 
share|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

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

test -d path

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

share|improve this answer

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

e.g.:

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

echos: root dir.

share|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
[ -d /home/bla/ ] && echo "exits"
share|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

Assuming your shell is BASH:

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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.