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


当前回答

DIRECTORY=/tmp

if [ -d "$DIRECTORY" ]; then
    echo "Exists"
fi

联机尝试

其他回答

从脚本文件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

更多功能使用查找

检查子目录中是否存在文件夹:find=`find-type d-name“myDirectory”`如果[-n“$found”]然后#变量“find”包含“myDirectory”所在的完整路径。#如果有多个名为“myDirectory”的文件夹,它可能包含多行。传真根据当前目录中的模式检查是否存在一个或多个文件夹:found=`find-maxdepth 1-type d-name“my*”`如果[-n“$found”]然后#变量“find”包含找到文件夹“my*”的完整路径。传真两种组合。在以下示例中,它检查当前目录中是否存在文件夹:find=`find-maxdeph 1-type d-name“myDirectory”`如果[-n“$found”]然后#变量'found'不为空=>“myDirectory”`存在。传真

我发现双括号版本的测试使编写逻辑测试更自然:

if [[ -d "${DIRECTORY}" && ! -L "${DIRECTORY}" ]] ; then
    echo "It's a bona-fide directory"
fi

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

使用-e检查将检查文件,其中包括目录。

if [ -e ${FILE_PATH_AND_NAME} ]
then
    echo "The file or directory exists."
fi