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


当前回答

您可以使用test-d(参见man test)。

-d file如果文件存在并且是目录,则为True。

例如:

test -d "/etc" && echo Exists || echo Does not exist

注意:测试命令与条件表达式[(参见:man[)相同,因此它可以跨shell脚本移植。

[-这是测试内置的同义词,但最后一个参数必须是文字],以匹配开头[。

有关可能的选项或进一步帮助,请检查:

帮助[帮助测试人工测试或人工[

其他回答

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

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

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块执行。

[[ -d "$DIR" && ! -L "$DIR" ]] && echo "It's a directory and not a symbolic link"

注:引用变量是一种很好的做法。

说明:

-d: 检查是否是目录-五十: 检查是否是符号链接

要检查目录是否存在,可以使用简单的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
if [ -d "$Directory" -a -w "$Directory" ]
then
    #Statements
fi

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

注意-d测试可能会产生一些令人惊讶的结果:

$ ln -s tmp/ t
$ if [ -d t ]; then rmdir t; fi
rmdir: directory "t": Path component not a directory

下面的文件:“什么时候目录不是目录?”答案:“当它是指向目录的符号链接时。”

if [ -d t ]; then 
   if [ -L t ]; then 
      rm t
   else 
      rmdir t
   fi
fi

您可以在Bash手册中找到有关Bash条件表达式、内置命令和[[复合命令的更多信息。