什么命令检查Bash shell脚本中是否存在目录?
当前回答
在Bash脚本中引用变量时,始终将变量括在双引号中。
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists, even if it contains spaces
fi
现在的孩子们在他们的目录名中添加空格和许多其他有趣的字符。(空间!在我的时代,我们没有花哨的空间!)有一天,这些孩子中的一个会运行你的脚本,$DIRECTORY设置为“My M0viez”,你的脚本就会崩溃。你不想这样。所以使用双引号。
其他回答
注意-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条件表达式、内置命令和[[复合命令的更多信息。
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists
fi
这不是完全正确的。。。
如果要转到该目录,还需要具有该目录的执行权限。也许你也需要写权限。
因此:
if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
# ... to go to that directory (even if DIRECTORY is a link)
cd $DIRECTORY
pwd
fi
if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
# ... to go to that directory and write something there (even if DIRECTORY is a link)
cd $DIRECTORY
touch foobar
fi
要检查多个目录,请使用以下代码:
if [ -d "$DIRECTORY1" ] && [ -d "$DIRECTORY2" ] then
# Things to do
fi
使用-e检查将检查文件,其中包括目录。
if [ -e ${FILE_PATH_AND_NAME} ]
then
echo "The file or directory exists."
fi
在三元形式中,
[ -d "$directory" ] && echo "exist" || echo "not exist"
通过测试:
test -d "$directory" && echo "exist" || echo "not exist"
推荐文章
- 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和标准输出到不同的文件在同一行脚本?
- 如何循环通过一个目录递归删除具有某些扩展名的文件
- 在Bash中获取日期(比当前时间早一天)
- Linux: kill后台任务