什么命令检查Bash shell脚本中是否存在目录?


当前回答

if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

上述代码检查目录是否存在以及是否可写。

其他回答

较短形式:

# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"

注意-d测试可能会产生一些令人惊讶的结果:

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

下面的文件:“什么时候目录不是目录?”答案:“当它是指向目录的符号链接时。”

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

您可以在Bash手册中找到有关Bash条件表达式、内置命令和[[复合命令的更多信息。

要检查多个目录,请使用以下代码:

if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
    # Things to do
fi
file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;

您可以使用test-d(参见man test)。

-d file如果文件存在并且是目录,则为True。

例如:

test -d "/etc" && echo Exists || echo Does not exist

注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。

[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。

有关可能的选项或进一步帮助,请检查:

帮助[帮助测试人工测试或人工[