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

查看:153
本文介绍了如何检查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 在另一个答案中对此原因进行了解释.


Take particular note of the double-quotes used to wrap the variables. The reason for this is explained by 8jean in another answer.

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

If the variables contain spaces or other unusual characters it will probably cause the script to fail.

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

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