繁体   English   中英

为什么这个bash脚本给我一个关于“缺少`]'”的错误?

[英]Why is this bash script giving me an error about “missing `]'”?

我必须检查文件dir1dir2是否存在。 然后,递归删除它们,否则打印一些消息。 这是我的代码:

if [ -d "dir1"] && [-d "dir2"]; then
 echo "directory exists"
 echo "deleting existing files...."
sleep 2
 rm -r dir1
 rn -r dir1
 echo "exisitng files deleted!!"
else   
 echo "directory does not exist"
fi

这给我一个错误,说缺少表达。

./check.sh: line 16: [: missing `]'
directory does not exist.

怎么了

该行的书写方式不正确:

if [ -d "dir1"] && [-d "dir2"]; then
             ^      ^       ^
              missing spaces

应该

if [ -d "dir1" ] && [ -d "dir2" ]; then

然后你有这个:

rn -r dir1
 ^
 rn does not exist

这应该是rmdir2因为您已经删除了dir1

rm -r dir2

您需要具备:

[ -d "dir" ]

不是

[-d "dir"]

注意空格。 有关其他问题,请参阅fedorqui的答案。

提出了更强大的解决方案(根据您的喜好添加更多详细的输出):

#!/bin/sh

dirs="dir1 dir2" # Directory names may not contain spaces
for dir in $dirs; do
    [ ! -d $dir ] || rm -r $dir || echo "failed to remove $dir"
done

请注意,使用&&的解决方案要求同时存在两个目录才能触发删除。 我不知道那是否是你的意图。 我的解决方案查找dirs变量中是否存在任何dirs ,在这种情况下,尝试删除它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM