检查一个目录是否存在于一个shell脚本中

在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所指出的(感谢Jon),如果您不考虑到目录的符号链接也会通过此检查,则后续命令可能无法按预期工作。 例如运行这个:

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在另一个答案中解释。

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


记住在bash脚本中引用变量时总是用双引号包装变量。 现在的孩子们长大了,他们的想法是他们的目录名中可以有空间和许多其他有趣的角色。 (空间!在我的日子里,我们没有任何花哨的空间!))

有一天,其中一个孩子会用$DIRECTORY设置为"My M0viez"来运行你的脚本,你的脚本将会炸毁。 你不想那样。 所以使用这个。

if [ -d "$DIRECTORY" ]; then
    # Will enter here if $DIRECTORY exists, even if it contains spaces
fi

我发现test的双括号版本使编写逻辑测试更加自然:

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
    echo "It's a bona-fide directory"
fi
链接地址: http://www.djcxy.com/p/359.html

上一篇: Check if a directory exists in a shell script

下一篇: Listen for function after other function is finished