检查目录是否不存在[重复]

时间:2021-02-27 08:06:32

This question already has an answer here:

这个问题在这里已有答案:

I have written a script to check in var/log directory, and it takes all the directories in there and checks if there is an archive directory in those directories. If an archive directory not exist, I want to create it, but once it's created the script tries to create it again.

我编写了一个脚本来检查var / log目录,它会获取其中的所有目录并检查这些目录中是否有归档目录。如果存档目录不存在,我想创建它,但是一旦创建它,​​脚本就会尝试再次创建它。

vdir=$(sudo sh -c "find /var/log/ -maxdepth 1 -type d ! -name "archive"" )
for i in $vdir ;do
    echo $i
    if [[ ! -d $i/$arc ]];then
        sudo sh -c "mkdir $i/$arc"
        echo "$date:$HN:Creating:$i/$arc:directory" >> logrotation.log
    fi
done

When I execute above code it gives me this error. Seems the script is not checking the condition.

当我执行上面的代码时,它给了我这个错误。似乎脚本没有检查条件。

mkdir: cannot create directory ‘/var/log/speech-dispatcher/archive’: File exists

1 个解决方案

#1


11  

The issue is that you have two [ symbols. You only need one:

问题是你有两个[符号。你只需要一个:

          if [ ! -d $i/$arc ];then

An additional point: some shell versions don't handle the ; being right next to the closing bracket. Thus, I'd suggest formatting like this for best compatibility:

另外一点:一些shell版本不处理;紧靠闭幕式。因此,我建议像这样格式化以获得最佳兼容性:

          if [ ! -d $i/$arc ] ; then

Edit: since the above didn't help you, more thoughts:

编辑:由于以上对你没有帮助,更多的想法:

It's also entirely possible that your script, running as you, can't actually read the contents of the $i directory and thus the test will always fail (or succeed, actually). But, when you create the directory as root via sudo, it already exists.

您的脚本也可能无法实际读取$ i目录的内容,因此测试将始终失败(或实际成功)。但是,当您通过sudo以root身份创建目录时,它已经存在。

[It would also be more efficient to run the entire script under sudo rather than just certain pieces of it.]

[在sudo下运行整个脚本而不仅仅是某些部分也会更有效。]

#1


11  

The issue is that you have two [ symbols. You only need one:

问题是你有两个[符号。你只需要一个:

          if [ ! -d $i/$arc ];then

An additional point: some shell versions don't handle the ; being right next to the closing bracket. Thus, I'd suggest formatting like this for best compatibility:

另外一点:一些shell版本不处理;紧靠闭幕式。因此,我建议像这样格式化以获得最佳兼容性:

          if [ ! -d $i/$arc ] ; then

Edit: since the above didn't help you, more thoughts:

编辑:由于以上对你没有帮助,更多的想法:

It's also entirely possible that your script, running as you, can't actually read the contents of the $i directory and thus the test will always fail (or succeed, actually). But, when you create the directory as root via sudo, it already exists.

您的脚本也可能无法实际读取$ i目录的内容,因此测试将始终失败(或实际成功)。但是,当您通过sudo以root身份创建目录时,它已经存在。

[It would also be more efficient to run the entire script under sudo rather than just certain pieces of it.]

[在sudo下运行整个脚本而不仅仅是某些部分也会更有效。]