什么命令检查Bash shell脚本中是否存在目录?
当前回答
[ -d ~/Desktop/TEMPORAL/ ] && echo "DIRECTORY EXISTS" || echo "DIRECTORY DOES NOT EXIST"
其他回答
较短形式:
# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
我发现双括号版本的测试使编写逻辑测试更自然:
if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
echo "It's a bona-fide directory"
fi
要检查多个目录,请使用以下代码:
if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
# Things to do
fi
[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"
注:引用变量是一种很好的做法。
说明:
-d: 检查是否是目录-五十: 检查是否是符号链接
注意-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条件表达式、内置命令和[[复合命令的更多信息。