什么命令检查Bash shell脚本中是否存在目录?
当前回答
要检查目录是否存在,可以使用简单的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
其他回答
注意-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条件表达式、内置命令和[[复合命令的更多信息。
更多功能使用查找
检查子目录中是否存在文件夹: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结构,如下所示:
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
检查目录是否存在,否则创建一个:
[ -d "$DIRECTORY" ] || mkdir $DIRECTORY
file="foo"
if [[ -e "$file" ]]; then echo "File Exists"; fi;
推荐文章
- 如何使用查找命令从列表中查找所有具有扩展名的文件?
- 如何获得一个变量值,如果变量名存储为字符串?
- RVM不是一个函数,用' RVM use…’不会起作用
- 如何打破一个循环在Bash?
- 如何从终端机发送电子邮件?
- 如何将文件指针(file * fp)转换为文件描述符(int fd)?
- Linux Bash中双&和分号有什么区别?
- 如何合并2 JSON对象从2个文件使用jq?
- 在Bash中模拟do-while循环
- 在Bash中将输出赋给变量
- 如何在Mac OS X 10.6中使硬件发出哔哔声
- Node.js同步执行系统命令
- 从Docker容器获取环境变量
- 如何重定向标准derr和标准输出到不同的文件在同一行脚本?
- 如何循环通过一个目录递归删除具有某些扩展名的文件