Reputation: 4271
Background:
I'm trying to add something to my bash profile to see if a backup is outdated and then make a quick backup if not.
The Question
Basically I'm trying to see if a file is older than an arbitrary date. I can find the most recently updated file with
lastbackup=$(ls -t file | head -1)
And I can get last modified date with
stat -f "%Sm" $lastbackup
But I can't figure out how to compare that time with bash functions, or how to make a timestamp, etc.
All the other answers I found seem to use the non mac versions of stat
with differently supported flags. Looking for any clues!
Upvotes: 1
Views: 2340
Reputation: 5372
You can use seconds since the epoch for the actual date and the last file change and then decide if a backup is needed based on the difference of seconds.
Something like this: (edit: changed stat parameters to match OS X options)
# 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
Upvotes: 3
Reputation: 16
The find command will do what you're looking for quite nicely. Say you want to ensure you have a backup that is no older than 1 day every day (that you login), here is a test setup with two files, the find syntax, and the output you will see.
# 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
If you view the manpage for find, look at the -atime switch for details on other units you can use (e.g. hours, minutes).
Upvotes: 0