什么命令检查Bash shell脚本中是否存在目录?
当前回答
实际上,您应该使用几种工具来获得防弹方法:
DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # Now you're testing
echo "It's a dir";
fi
只要使用“${}”,就不必担心空格和特殊字符。
请注意,[[]]不像[]那样可移植,但由于大多数人都使用现代版本的Bash(毕竟,大多数人甚至不使用命令行:-p),所以好处大于麻烦。
其他回答
在三元形式中,
[ -d "$directory" ] && echo "exist" || echo "not exist"
通过测试:
test -d "$directory" && echo "exist" || echo "not exist"
较短形式:
# if $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"
要检查目录是否存在:
if [ -d "$DIRECTORY" ]; then
echo "$DIRECTORY does exist."
fi
要检查目录是否不存在:
if [ ! -d "$DIRECTORY" ]; then
echo "$DIRECTORY does not exist."
fi
然而,正如JonEricson指出的,如果不考虑到指向目录的符号链接也会通过此检查,则后续命令可能无法按预期工作。例如,执行以下操作:
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在另一个答案中解释了这一点的原因。
如果变量包含空格或其他异常字符,则可能会导致脚本失败。
您可以使用test-d(参见man test)。
-d file如果文件存在并且是目录,则为True。
例如:
test -d "/etc" && echo Exists || echo Does not exist
注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。
[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。
有关可能的选项或进一步帮助,请检查:
帮助[帮助测试人工测试或人工[
我发现双括号版本的测试使编写逻辑测试更自然:
if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
echo "It's a bona-fide directory"
fi