linux - 检查目录是否不存在

标签 linux bash shell

<分区>

我写了一个脚本来检查 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

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

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

最佳答案

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

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

另外一点:某些 shell 版本不处理右括号旁边的 ;。因此,我建议采用这样的格式以获得最佳兼容性:

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

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

您的脚本也完全有可能无法真正读取 $i 目录的内容,因此测试总是会失败(或实际上成功)。但是,当您通过 sudo 将目录创建为根目录时,它已经存在。

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

关于linux - 检查目录是否不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41868707/

相关文章:

linux - 如何在 GRUNT shell 中取消命令

linux - 如何在 freebsd 的不同 session 中执行子进程

bash - 如何将 Bash 数组偏移量与默认值结合起来?

bash - 如何在 gnuplot 上将变量传递给 -e?

linux - 将一个二进制文件的部分 stdout 输出替换为另一个二进制文件的输出的 unix 命令是什么?

c - 变量的值存储在 C 中的位置

linux - 升级到 docker 1.5 后无法启动 linux 容器

bash - 使用 read() 或 run() 运行 bash 命令时,我应该如何转义 '&&' 和其他特殊字符?

shell - 与 Linux split 相反

linux - 如何在Linux中控制并行任务以避免过多的上下文切换