【问题标题】:Combing several subqueries in IF statement在 IF 语句中组合几个子查询
【发布时间】:2015-04-01 21:45:54
【问题描述】:

当前目录包含不断出现的新日志。
/tmp/logstash/ 目录包含我将比较新日志的日志

条件:
如果新日志具有相同的名称和 /tmp/logstash 中已经存在的大小,我应该得到“相同的文件已经存在”消息。
否则脚本会将新日志移动到 /tmp/logstash/。

注意,如果名称相同但大小不同,脚本仍应将新文件移动到 tmp/logstash/

我的脚本如下,它不能与'then && if'组合正常工作,你能帮忙解决它吗?

for file in *.log; do
    new_filesize=$(du -b "$file" | cut -f 1)
    if [[ -e /tmp/logstash/"$file" ]]
    then
        old_filesize=$(du -b /tmp/logstash/"$file" | cut -f 1) &&
            if [[ "$new_filesize"="$old_filesize" ]]; then
                echo "The file already exists"
            fi
    else mv $file /tmp/logstash
    fi
done

【问题讨论】:

    标签: bash shell if-statement for-loop


    【解决方案1】:

    条件表达式中的= 周围需要空格:

    if [[ $new_filesize = $old_filesize ]]; then
    

    没有空格,您只是在测试连接的字符串"$new_filesize"="$old_filesize" 是否为非空。

    【讨论】:

      【解决方案2】:

      测试是否存在,如果存在则测试文件大小,否则复制

      根据您在 cmets 中的要求。下面测试old_file是否存在。如果是,则检查new_fileold_file 之间的大小是否不同。如果它们不同,则将 new_file 移动到 /tmp/logstash/ 替换 old_file。如果old_file 存在并且文件大小相等,那么它将echo "The file already exists"。如果old_file 不存在,则只需将new_file 复制到/tmp/logstash/

      for file in *.log; do
          if [ -e /tmp/logstash/"$file" ]; then
              if [ $(stat %s "$file") -ne $(stat %s /tmp/logstash/"$file") ]
                  mv -f "$file" /tmp/logstash
              else
                  echo "The file already exists"
              fi
          else
              cp "$file" /tmp/logstash/"$file"
          fi
      done
      

      注意:记住引用你的变量


      使用变量 new_filesizeold_filesize

      for file in *.log; do
          new_filesize=$(stat %s "$file")
          if [ -e /tmp/logstash/"$file" ]; then
              old_filesize=$(stat %s /tmp/logstash/"$file")
              if [ $new_filesize -ne $old_filesize ]
                  mv -f "$file" /tmp/logstash
              else
                  echo "The file already exists"
              fi
          else
              cp "$file" /tmp/logstash/"$file"
          fi
      done
      

      注意:mv -f 已添加到存在old_file 的所有情况中,以防止由于现有文件而导致移动失败。

      【讨论】:

      • 为什么是-gt 而不是-ne
      • 好点。我只是在想newer,但-ne 也可以。
      • @Barmar 我猜他没有告诉我们他们来自哪里,所以他们可能更老。已修复,谢谢。
      • 现在我看到你在比较模组时间。我以为是尺寸,更容易朝不同方向波动。
      • 您的观点仍然有效。如果他们从其他地方的较早来源的rsync -acp -a 到达那里,-ne 将在-gt 不会捕获它的地方。
      猜你喜欢
      • 2022-11-25
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多