Check if a directory exists in a shell script

2018-12-31 14:29发布

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

标签: shell unix posix
30条回答
何处买醉
2楼-- · 2018-12-31 15:09

The ls command in conjunction with -l (long listing) option returns attributes information about files and directories.
In particular the first character of ls -l output it is usually a d or a - (dash). In case of a d the one listed is a directory for sure.

The following command in just one line will tell you if the given ISDIR variable contains a path to a directory or not:

[[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] &&
    echo "YES, $ISDIR is a directory." || 
    echo "Sorry, $ISDIR is not a directory"

Practical usage:

    [claudio@nowhere ~]$ ISDIR="$HOME/Music" 
    [claudio@nowhere ~]$ ls -ld "$ISDIR"
    drwxr-xr-x. 2 claudio claudio 4096 Aug 23 00:02 /home/claudio/Music
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." ||
        echo "Sorry, $ISDIR is not a directory"
    YES, /home/claudio/Music is a directory.

    [claudio@nowhere ~]$ touch "empty file.txt"
    [claudio@nowhere ~]$ ISDIR="$HOME/empty file.txt" 
    [claudio@nowhere ~]$ [[ $(ls -ld "$ISDIR" | cut -c1) == 'd' ]] && 
        echo "YES, $ISDIR is a directory." || 
        echo "Sorry, $ISDIR is not a directoy"
    Sorry, /home/claudio/empty file.txt is not a directory
查看更多
浅入江南
3楼-- · 2018-12-31 15:10

Type this code on the bash promt

if [ -d "$DIRECTORY" ]; then
  # if true this block of code will execute
fi
查看更多
春风洒进眼中
4楼-- · 2018-12-31 15:11

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
查看更多
无色无味的生活
5楼-- · 2018-12-31 15:12

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.

查看更多
忆尘夕之涩
6楼-- · 2018-12-31 15:12

To check more than one directory use this code:

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi
查看更多
初与友歌
7楼-- · 2018-12-31 15:12

Below find can be used,

find . -type d -name dirname -prune -print
查看更多
登录 后发表回答