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

后端 未结 30 1989
猫巷女王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:31
    if [ -d "$Directory" -a -w "$Directory" ]
    then
        #Statements
    fi
    

    The above code checks if the directory exists and if it is writable.

    0 讨论(0)
  • 2020-11-22 11:33
    file="foo" 
    if [[ -e "$file" ]]; then echo "File Exists"; fi;
    
    0 讨论(0)
  • 2020-11-22 11:34

    I find the double-bracket version of test makes writing logic tests more natural:

    if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
        echo "It's a bona-fide directory"
    fi
    
    0 讨论(0)
  • 2020-11-22 11:34
    [[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"
    

    N.B: Quoting variables is a good practice.

    Explanation:

    • -d: check if it's a directory
    • -L: check if it's a symbolic link
    0 讨论(0)
  • 2020-11-22 11:35

    To check if a directory exists you can use a simple if structure like this:

    if [ -d directory/path to a directory ] ; then
    # Things to do
    
    else #if needed #also: elif [new condition]
    # Things to do
    fi
    

    You can also do it in the negative:

    if [ ! -d directory/path to a directory ] ; then
    # Things to do when not an existing directory
    

    Note: Be careful. Leave empty spaces on either side of both opening and closing braces.

    With the same syntax you can use:

    -e: any kind of archive
    
    -f: file
    
    -h: symbolic link
    
    -r: readable file
    
    -w: writable file
    
    -x: executable file
    
    -s: file size greater than zero
    
    0 讨论(0)
  • 2020-11-22 11:36

    Use the file program. Considering all directories are also files in Linux, issuing the following command would suffice:

    file $directory_name

    Checking a nonexistent file: file blah

    Output: cannot open 'blah' (No such file or directory)

    Checking an existing directory: file bluh

    Output: bluh: directory

    0 讨论(0)
提交回复
热议问题