在Bash shell脚本中,可以使用什么命令来检查目录是否存在?
要检查shell脚本中是否存在目录,可以使用以下命令:
if [ -d "$DIRECTORY" ]; then
# Control will enter here if $DIRECTORY exists.
fi
或检查目录是否不存在:
if [ ! -d "$DIRECTORY" ]; then
# Control will enter here if $DIRECTORY doesn't exist.
fi
但是,正如乔恩·埃里克森(Jon Ericson)所指出的,如果您不考虑到目录的符号链接也将通过此检查,则后续命令可能无法按预期运行。例如运行此:
ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then
rmdir "$SYMLINK"
fi
会产生错误信息:
rmdir: failed to remove `symlink': Not a directory
因此,如果后续命令需要目录,则可能必须区别对待符号链接:
if [ -d "$LINK_OR_DIR" ]; then
if [ -L "$LINK_OR_DIR" ]; then
# It is a symlink!
# Symbolic link specific commands go here.
rm "$LINK_OR_DIR"
else
# It's a directory!
# Directory command goes here.
rmdir "$LINK_OR_DIR"
fi
fi
请特别注意用于包装变量的双引号。8jean在另一个答案中对此进行了解释。
如果变量包含空格或其他异常字符,则可能会导致脚本失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句