如何确定文件最近是否在Mac上使用bash进行了修改



背景:

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

问题

基本上,我正在尝试查看文件是否早于任意日期。我可以找到最近更新的文件

lastbackup=$(ls -t file | head -1) 

我可以得到上次修改日期

stat -f "%Sm" $lastbackup

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

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

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

像这样:(编辑:更改了统计参数以匹配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

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 开关,了解可以使用的其他单位的详细信息(例如小时、分钟(。

最新更新