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


当前回答

从脚本文件myScript.sh:

if [ -d /home/ec2-user/apache-tomcat-8.5.5/webapps/Gene\ Directory ]; then
   echo "Directory exists!"
   echo "Great"
fi

Or

if [ -d '/home/ec2-user/apache-tomcat-8.5.5/webapps/Gene Directory' ]; then
   echo "Directory exists!"
   echo "Great"
fi

其他回答

要检查目录是否存在:

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 [ -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

只有在执行时,您所在的目录中恰好有一个子目录,您才能成功执行。

我理解这样的初始问题:无论用户在文件系统中的位置如何,都要验证目录是否存在。因此,使用命令“find”可能会奏效:

dir=" "
echo "Input directory name to search for:"
read dir
find $HOME -name $dir -type d

此解决方案很好,因为它允许使用通配符,这是搜索文件/目录时的一个有用功能。唯一的问题是,如果搜索到的目录不存在,“find”命令将不会将任何内容打印到标准输出中(对我来说这不是一个优雅的解决方案),但仍然会有一个零出口。也许有人可以改进一下。

if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

上述代码检查目录是否存在以及是否可写。

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

如果要检查目录是否存在,无论它是真实目录还是符号链接,请使用以下命令:

ls $DIR
if [ $? != 0 ]; then
        echo "Directory $DIR already exists!"
        exit 1;
fi
echo "Directory $DIR does not exist..."

解释:如果目录或符号链接不存在,则“ls”命令会给出错误“ls:/x:No such file or directory”,并将返回代码设置为非空(通常为“1”),您可以通过“$?”检索该代码。请确保在调用“ls”后直接检查返回代码。