0

我必须检查文件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.

这里有什么问题?

4

2 回答 2

7

此行未正确编写:

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

应该

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

然后你有这个:

rn -r dir1
 ^
 rn does not exist

这应该是因为你已经删除rm了:dir2dir1

rm -r dir2
于 2013-07-10T09:27:24.683 回答
3

你需要有:

[ -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变量中的任何目录是否存在,并在这种情况下尝试删除它们。

于 2013-07-10T09:27:58.830 回答