什么命令检查Bash shell脚本中是否存在目录?


当前回答

file="foo" 
if [[ -e "$file" ]]; then echo "File Exists"; fi;

其他回答

你有没有考虑过只做你想做的事,而不是三思而后行?

也就是说,如果您想在输入目录之前检查其是否存在,请尝试执行以下操作:

if pushd /path/you/want/to/enter; then
    # Commands you want to run in this directory
    popd
fi

如果您给pushd的路径存在,您将输入它,它将以0退出,这意味着将执行语句的then部分。如果它不存在,什么都不会发生(除了一些输出说目录不存在,这可能对调试有帮助的副作用)。

这似乎比这更好,这需要重复自己:

if [ -d /path/you/want/to/enter ]; then
    pushd /path/you/want/to/enter
    # Commands you want to run in this directory
    popd
fi

同样的方法也适用于cd、mv、rm等……如果您在不存在的文件上尝试它们,它们将以错误退出并打印一条消息表示不存在,然后将跳过您的then块。如果您在确实存在的文件上尝试它们,则命令将执行并退出,状态为0,从而允许您的then块执行。

要检查目录是否存在:

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 $DIR is a directory, then print yes
[ -d "$DIR" ] && echo "Yes"

根据Jonathan的评论:

如果您想创建目录,但它还不存在,那么最简单的方法是使用mkdir-p创建目录-以及路径上的任何缺失目录-如果目录已经存在,则不会失败,因此您可以使用以下方法一次性完成:

mkdir -p /some/directory/you/want/to/exist || exit 1

要检查目录是否存在,可以使用简单的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