小编典典

如何检查 Bash shell 脚本中是否存在目录?

javascript

在 Bash shell 脚本中,可以使用什么命令来检查目录是否存在?


阅读 254

收藏
2022-01-11

共1个答案

小编典典

要检查 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在另一个答案中解释了其原因。

如果变量包含空格或其他异常字符,则可能会导致脚本失败。

2022-01-11