【问题标题】:How to determine if a file has been modified recently with bash on mac如何确定最近是否在 mac 上使用 bash 修改了文件
【发布时间】:2018-02-02 04:23:34
【问题描述】:

背景:

我正在尝试在我的 bash 配置文件中添加一些内容,以查看备份是否已过时,如果没有,则进行快速备份。

问题

基本上,我试图查看文件是否早于任意日期。我可以使用

找到最近更新的文件
lastbackup=$(ls -t file | head -1) 

我可以使用

获取上次修改日期
stat -f "%Sm" $lastbackup

但我不知道如何将该时间与 bash 函数进行比较,或者如何制作时间戳等。

我发现的所有其他答案似乎都使​​用了 stat 的非 mac 版本,并带有不同的支持标志。寻找任何线索!

【问题讨论】:

    标签: bash macos shell terminal


    【解决方案1】:

    您可以使用自纪元以来的秒数作为实际日期和最后一次文件更改,然后根据秒数的差异决定是否需要备份。

    类似这样的:(编辑:更改统计参数以匹配 OS X 选项)

    # today in seconds since the epoch
    today=$(date +%s)
    # last file change in seconds since the epoch
    lastchange=$(stat -f '%m' thefile)
    # number of seconds between today and the last change
    timedelta=$((today - lastchange))
    # decide to do a backup if the timedelta is greater than
    # an arbitrary number of second
    # ie. 7 days (7d * 24h * 60m * 60s = 604800 seconds)
    if [ $timedelta -gt 604800 ]; then
       do_backup
    elif
    

    【讨论】:

    • 是的,但是stat的mac版没有-c选项
    • 我手头没有 OS X,但 stat 的在线手册页说您有 -r 和 -f 格式选项。您不能将它们结合起来以获取自纪元以来的最后更改日期(以秒为单位)?
    • stat -r -f '%m' $lastbackup 的输出是什么?如果我的手册页正确,它将为您提供自纪元以来的最后一次更改(以秒为单位)。
    • 您不能同时使用-r-f,但如果没有-r,这似乎效果很好。我将选择另一个答案,因为它似乎在我的用例中效果更好,但如果我能接受两个我会的。
    • 不用担心。我们以快乐为目标。 :-)
    【解决方案2】:

    find 命令可以很好地完成您要查找的内容。假设您要确保每天(您登录)拥有不超过 1 天的备份,这是一个包含两个文件、查找语法和您将看到的输出的测试设置。

    # Create a backup directory and cd to it
    mkdir backups; cd backups
    
    # Create file, oldfile and set oldfile last mod time to 2 days ago
    touch file
    touch -a -m -t 201801301147 oldfile
    
    # Find files in this folder with modified time within 1 day ago;
    # will only list file
    find . -type f -mtime -1
    
    # If you get no returned files from find, you know you need to run
    # a backup.  You could do this (replace run-backup with your backup command):
    lastbackup=$(find . -type f -mtime -1)
    if [ -z "$lastbackup" ]; then
      run-backup
    fi
    

    如果您查看 find 的手册页,请查看 -atime 开关以了解您可以使用的其他单位的详细信息(例如小时、分钟)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-12
      • 1970-01-01
      • 2011-10-28
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      相关资源
      最近更新 更多