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

后端 未结 30 1943
猫巷女王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:37

    More features using find

    • Check existence of the folder within sub-directories:

      found=`find -type d -name "myDirectory"`
      if [ -n "$found"]
      then
          # The variable 'found' contains the full path where "myDirectory" is.
          # It may contain several lines if there are several folders named "myDirectory".
      fi
      
    • Check existence of one or several folders based on a pattern within the current directory:

      found=`find -maxdepth 1 -type d -name "my*"`
      if [ -n "$found"]
      then
          # The variable 'found' contains the full path where folders "my*" have been found.
      fi
      
    • Both combinations. In the following example, it checks the existence of the folder in the current directory:

      found=`find -maxdepth 1 -type d -name "myDirectory"`
      if [ -n "$found"]
      then
          # The variable 'found' is not empty => "myDirectory"` exists.
      fi
      
    0 讨论(0)
  • 2020-11-22 11:37

    Actually, you should use several tools to get a bulletproof approach:

    DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
    if [[ -d "${DIR_PATH}" ]] ; Then # Now you're testing
        echo "It's a dir";
    fi
    

    There isn't any need to worry about spaces and special characters as long as you use "${}".

    Note that [[]] is not as portable as [], but since most people work with modern versions of Bash (since after all, most people don't even work with command line :-p), the benefit is greater than the trouble.

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

    Remember to always wrap variables in double quotes when referencing them in a Bash script. Kids these days grow up with the idea that they can have spaces and lots of other funny characters in their directory names. (Spaces! Back in my days, we didn't have no fancy spaces! ;))

    One day, one of those kids will run your script with $DIRECTORY set to "My M0viez" and your script will blow up. You don't want that. So use this.

    if [ -d "$DIRECTORY" ]; then
        # Will enter here if $DIRECTORY exists, even if it contains spaces
    fi
    
    0 讨论(0)
  • 2020-11-22 11:38

    Here's a very pragmatic idiom:

    (cd $dir) || return # Is this a directory,
                        # and do we have access?
    

    I typically wrap it in a function:

    can_use_as_dir() {
        (cd ${1:?pathname expected}) || return
    }
    

    Or:

    assert_dir_access() {
        (cd ${1:?pathname expected}) || exit
    }
    

    The nice thing about this approach is that I do not have to think of a good error message.

    cd will give me a standard one line message to standard error already. It will also give more information than I will be able to provide. By performing the cd inside a subshell ( ... ), the command does not affect the current directory of the caller. If the directory exists, this subshell and the function are just a no-op.

    Next is the argument that we pass to cd: ${1:?pathname expected}. This is a more elaborate form of parameter substitution which is explained in more detail below.

    Tl;dr: If the string passed into this function is empty, we again exit from the subshell ( ... ) and return from the function with the given error message.


    Quoting from the ksh93 man page:

    ${parameter:?word}
    

    If parameter is set and is non-null then substitute its value; otherwise, print word and exit from the shell (if not interactive). If word is omitted then a standard message is printed.

    and

    If the colon : is omitted from the above expressions, then the shell only checks whether parameter is set or not.

    The phrasing here is peculiar to the shell documentation, as word may refer to any reasonable string, including whitespace.

    In this particular case, I know that the standard error message 1: parameter not set is not sufficient, so I zoom in on the type of value that we expect here - the pathname of a directory.

    A philosophical note:

    The shell is not an object oriented language, so the message says pathname, not directory. At this level, I'd rather keep it simple - the arguments to a function are just strings.

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

    Check if the directory exists, else make one:

    [ -d "$DIRECTORY" ] || mkdir $DIRECTORY
    
    0 讨论(0)
  • 2020-11-22 11:38

    Using the -e check will check for files and this includes directories.

    if [ -e ${FILE_PATH_AND_NAME} ]
    then
        echo "The file or directory exists."
    fi
    
    0 讨论(0)
提交回复
热议问题