如何检查 Bash shell 脚本中是否存在目录? [英] How can I check if a directory exists in a Bash shell script?

查看:34
本文介绍了如何检查 Bash shell 脚本中是否存在目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What command can be used to check if a directory exists or not, within a Bash shell script?

推荐答案

要检查 shell 脚本中是否存在目录,可以使用以下命令:

To check if a directory exists in a shell script, you can use the following:

if [ -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY exists.
fi

或者检查目录是否不存在:

Or to check if a directory doesn't exist:

if [ ! -d "$DIRECTORY" ]; then
  # Control will enter here if $DIRECTORY doesn't exist.
fi

<小时>

但是,正如 Jon Ericson 指出的那样,如果您不考虑,后续命令可能无法按预期工作帐户的符号链接到目录也将通过此检查.例如.运行这个:


However, as Jon Ericson points out, subsequent commands may not work as intended if you do not take into account that a symbolic link to a directory will also pass this check. E.g. running this:

ln -s "$ACTUAL_DIR" "$SYMLINK"
if [ -d "$SYMLINK" ]; then 
  rmdir "$SYMLINK" 
fi

会产生错误信息:

rmdir: failed to remove `symlink': Not a directory

所以符号链接可能需要区别对待,如果后续命令需要目录:

So symbolic links may have to be treated differently, if subsequent commands expect directories:

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 the variables contain spaces or other unusual characters it will probably cause the script to fail.

这篇关于如何检查 Bash shell 脚本中是否存在目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆