什么命令检查Bash shell脚本中是否存在目录?
当前回答
或者对于完全无用的东西:
[ -d . ] || echo "No"
其他回答
或者对于完全无用的东西:
[ -d . ] || echo "No"
较短形式:
# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
要检查多个目录,请使用以下代码:
if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
# Things to do
fi
注意-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结构,如下所示:
if [ -d directory/path to a directory ] ; then
# Things to do
else #if needed #also: elif [new condition]
# Things to do
fi
你也可以用否定的方式:
if [ ! -d directory/path to a directory ] ; then
# Things to do when not an existing directory
注意:小心。在开口大括号和闭合大括号的两侧留出空白。
使用相同的语法,您可以使用:
-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