How can I check if a directory exists in a Bash shell script?

后端 未结 30 1940
猫巷女王i
猫巷女王i 2020-11-22 10:35

What command can be used to check if a directory exists or not, within a Bash shell script?

相关标签:
30条回答
  • 2020-11-22 11:12

    As per Jonathan's comment:

    If you want to create the directory and it does not exist yet, then the simplest technique is to use mkdir -p which creates the directory — and any missing directories up the path — and does not fail if the directory already exists, so you can do it all at once with:

    mkdir -p /some/directory/you/want/to/exist || exit 1
    
    0 讨论(0)
  • 2020-11-22 11:14
    1. A simple script to test if a directory or file is present or not:

       if [ -d /home/ram/dir ]   # For file "if [ -f /home/rama/file ]"
       then
           echo "dir present"
       else
           echo "dir not present"
       fi
      
    2. A simple script to check whether the directory is present or not:

       mkdir tempdir   # If you want to check file use touch instead of mkdir
       ret=$?
       if [ "$ret" == "0" ]
       then
           echo "dir present"
       else
           echo "dir not present"
       fi
      

      The above scripts will check if the directory is present or not

      $? if the last command is a success it returns "0", else a non-zero value. Suppose tempdir is already present. Then mkdir tempdir will give an error like below:

      mkdir: cannot create directory ‘tempdir’: File exists

    0 讨论(0)
  • 2020-11-22 11:15

    Note the -d test can produce some surprising results:

    $ ln -s tmp/ t
    $ if [ -d t ]; then rmdir t; fi
    rmdir: directory "t": Path component not a directory
    

    File under: "When is a directory not a directory?" The answer: "When it's a symlink to a directory." A slightly more thorough test:

    if [ -d t ]; then 
       if [ -L t ]; then 
          rm t
       else 
          rmdir t
       fi
    fi
    

    You can find more information in the Bash manual on Bash conditional expressions and the [ builtin command and the [[ compound commmand.

    0 讨论(0)
  • 2020-11-22 11:16
    DIRECTORY=/tmp
    
    if [ -d "$DIRECTORY" ]; then
        echo "Exists"
    fi
    

    Try online

    0 讨论(0)
  • 2020-11-22 11:16

    If you want to check if a directory exists, regardless if it's a real directory or a symlink, use this:

    ls $DIR
    if [ $? != 0 ]; then
            echo "Directory $DIR already exists!"
            exit 1;
    fi
    echo "Directory $DIR does not exist..."
    

    Explanation: The "ls" command gives an error "ls: /x: No such file or directory" if the directory or symlink does not exist, and also sets the return code, which you can retrieve via "$?", to non-null (normally "1"). Be sure that you check the return code directly after calling "ls".

    0 讨论(0)
  • 2020-11-22 11:17
    [ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
    
    0 讨论(0)
提交回复
热议问题