如何确定最近是否使用mac上的bash修改了文件

如何确定最近是否使用mac上的bash修改了文件,bash,macos,shell,terminal,Bash,Macos,Shell,Terminal,背景: 我正在尝试向我的bash配置文件中添加一些内容,以查看备份是否过时,如果不过时,则进行快速备份 问题 基本上我是想看看一个文件是否比一个任意的日期早。我可以使用查找最新更新的文件 lastbackup=$(ls -t file | head -1) 我可以用它来获得最后修改的日期 stat -f "%Sm" $lastbackup 但我不知道如何将时间与bash函数进行比较,或者如何制作时间戳,等等 我找到的所有其他答案似乎都使用了非mac版本的stat,并带有不同的支持标志。寻找

背景:

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

问题

基本上我是想看看一个文件是否比一个任意的日期早。我可以使用查找最新更新的文件

lastbackup=$(ls -t file | head -1) 
我可以用它来获得最后修改的日期

stat -f "%Sm" $lastbackup
但我不知道如何将时间与bash函数进行比较,或者如何制作时间戳,等等


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

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

# 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

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

您可以使用实际日期和上次文件更改的历元后的秒数,然后根据秒数差决定是否需要备份

类似这样的内容:(编辑:更改stat参数以匹配OSX选项)


是的,但是mac版的
stat
没有-c选项我手头没有OSX,但是stat的联机手册页上说你有-r和-f格式的选项。您不能将它们组合起来以秒为单位获取自纪元以来的最后更改日期吗?stat-r-f“%m”$lastbackup的输出是什么?如果我的手册页正确,它将在几秒钟内为您提供自新纪元以来的最后一次更改。您不能同时使用
-r
-f
,但如果没有
-r
,这似乎非常有效。我将使用另一个答案,因为它似乎更适合我的用例,但如果我能接受两个,我会接受。不用担心。我们追求快乐。:-)
# 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