26

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

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

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

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

37
$ if test -d /the/dir; then echo "exist"; fi 
  • I need it in command line, not in a script. – Emanuel Jan 21 '10 at 15:33
  • 5
    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
  • Not everybody's shell is bash! – reinierpost Nov 14 '16 at 10:29
  • @reinierpost then good luck to you... – Stefano Borini Nov 14 '16 at 10:57
  • @Stefano Borini: I still use tcsh because I'm too lazy to rewrite my .tcshrc. But more to the point: this might have explained the OP's problem. – reinierpost Nov 14 '16 at 23:25
10

Assuming your shell is BASH:

if [ -d /the/dir ]; then echo 'Exists'; else echo 'Not found'; fi
  • syntax error near unexpected token `then' – Emanuel Jan 21 '10 at 15:52
  • Then figure out what your shell is. Perhaps csh or tcsh? – reinierpost Nov 14 '16 at 10:28
8
[ -d /home/bla/ ] && echo "exits"
  • Can I have something like ELSE, to show a text even if the directory does´n exists? – Emanuel Jan 21 '10 at 15:40
  • Workaround: [ -d /home/bla/ ] && echo "exist" ; [ ! -d /home/bla/ ] && echo "doesnt exist" – learningloop Oct 5 '16 at 2:31
7

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

test -d path

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

  • The command doesn't appear to be doing by itself but when joined with a echo "Directory Exists". – Ejaz Aug 24 '16 at 21:17
2

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

e.g.:

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

will output: root dir.

  • [-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
0

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 ....]

  • Welcome to Super User! This duplicates another answer and adds no new content. Please don't post an answer unless you actually have something new to contribute. – DavidPostill Nov 14 '16 at 10:52

Your Answer

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