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

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

提交回复
热议问题