什么命令检查Bash shell脚本中是否存在目录?
当前回答
您可以使用test-d(参见man test)。
-d file如果文件存在并且是目录,则为True。
例如:
test -d "/etc" && echo Exists || echo Does not exist
注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。
[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。
有关可能的选项或进一步帮助,请检查:
帮助[帮助测试人工测试或人工[
其他回答
DIRECTORY=/tmp
if [ -d "$DIRECTORY" ]; then
echo "Exists"
fi
联机尝试
要检查目录是否存在:
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在另一个答案中解释了这一点的原因。
如果变量包含空格或其他异常字符,则可能会导致脚本失败。
要检查目录是否存在,可以使用简单的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
使用-e检查将检查文件,其中包括目录。
if [ -e ${FILE_PATH_AND_NAME} ]
then
echo "The file or directory exists."
fi
在三元形式中,
[ -d "$directory" ] && echo "exist" || echo "not exist"
通过测试:
test -d "$directory" && echo "exist" || echo "not exist"