什么命令检查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
推荐文章
- 如何从终端机发送电子邮件?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- Linux Bash中双&和分号有什么区别?
- 如何合并2 JSON对象从2个文件使用jq?
- 在Bash中模拟do-while循环
- 在Bash中将输出赋给变量
- 如何在Mac OS X 10.6中使硬件发出哔哔声
- Node.js同步执行系统命令
- 从Docker容器获取环境变量
- 如何重定向标准derr和标准输出到不同的文件在同一行脚本?
- 如何循环通过一个目录递归删除具有某些扩展名的文件
- 在Bash中获取日期(比当前时间早一天)
- Linux: kill后台任务
- 在OSX中永久设置PATH环境变量
- 删除Bash脚本中的重复条目