bash 检查目录是否不存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41868707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if directory does not exist
提问by SLS
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
回答by Wes Hardaker
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 下运行整个脚本也会更有效率,而不仅仅是其中的某些部分。]