【问题标题】:Find out if file has been modified within the last 2 minutes查看文件是否在过去 2 分钟内被修改
【发布时间】:2015-04-04 22:53:29
【问题描述】:

在 bash 脚本中,我想检查文件是否在过去 2 分钟内被更改。

我已经发现我可以使用stat file.ext -c %y 访问上次修改的日期。如何检查此日期是否超过两分钟?

【问题讨论】:

    标签: linux bash unix sh


    【解决方案1】:

    这是一个更简单的版本,它使用 shell 数学而不是 expr:

    秒(用于想法)

    echo $(( $(date +%s) - $(stat file.txt  -c %Y) ))
    

    分钟(回答)

    echo $(( ($(date +%s) - $(stat file.txt  -c %Y)) / 60 ))
    

    小时

    echo $(( ($(date +%s) - $(stat file.txt  -c %Y)) / 3600 ))
    

    【讨论】:

      【解决方案2】:

      这是一个测试文件是否早于 X 秒的解决方案。它不使用具有特定于平台语法的stat,也不使用粒度小于1 分钟的find

      interval_in_seconds=10
      filetime=$(date -r "$filepath" +"%s")
      now=$(date +"%s")
      timediff=$(expr $now - $filetime)
      if [ $timediff -ge $interval_in_seconds ]; then
        echo ""
      fi
      

      【讨论】:

        【解决方案3】:

        完成你所追求的脚本:

        #!/bin/sh
        
        # Input file
        FILE=/tmp/test.txt
        # How many seconds before file is deemed "older"
        OLDTIME=120
        # Get current and file times
        CURTIME=$(date +%s)
        FILETIME=$(stat $FILE -c %Y)
        TIMEDIFF=$(expr $CURTIME - $FILETIME)
        
        # Check if file older
        if [ $TIMEDIFF -gt $OLDTIME ]; then
           echo "File is older, do stuff here"
        fi
        

        如果您使用的是 macOS,请使用 stat -t %s -f %m $FILE 代替 FILETIME,如 Alcanzar 的评论中所述。

        【讨论】:

        • 如果其他人在 Mac 上找到此文件时间,请使用 stat -t %s -f %m $FILENAME
        【解决方案4】:

        我会这样做:(我会使用适当的临时文件)

        touch -d"-2min" .tmp
        [ "$file" -nt .tmp ] && echo "file is less than 2 minutes old"
        

        【讨论】:

        • 谢谢,这似乎是最干净最明智的做法!
        【解决方案5】:

        我通过这种方式解决了问题:获取文件的当前日期和最后修改日期(均采用 unix 时间戳格式)。从当前日期减去修改后的日期,然后除以 60(将其转换为分钟)。

        expr $(expr $(date +%s) - $(stat mail1.txt -c %Y)) / 60
        

        也许这不是最干净的解决方案,但效果很好。

        【讨论】:

          【解决方案6】:

          我认为这会有所帮助,

          find . -mmin -2 -type f -print
          

          还有,

          find / -fstype local -mmin -2
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-10-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-06
            相关资源
            最近更新 更多