This question pertains to taking action if a file has a modification date older than so many days. I'm sure it would be similar for creation date or access date, but for modification date, if I have:
file=path-name-to-some-file N=100 # for example, N is number of days
How would I do:
if file modification time is older than N days then fi
The modified date of a file or folder represents the last time that file or folder was updated.
Modified Time. The modified timestamp contains the time the file's data has been changed. It means when we make changes to the actual contents of the file, the file system will update the modification time.
You can manually change the Last Modified Date/Time for a file using a free software called Attribute Changer from http://www.petges.lu/. You will need to remember the modified date/time of your presentation file, modify the file and then use Attribute Changer to set the modified date/time to the previous one.
Use -mtime option with the find command to search files based on modification time followed by the number of days.
Several approaches are available. One is just to ask find
to do the filtering for you:
if [[ $(find "$filename" -mtime +100 -print) ]]; then echo "File $filename exists and is older than 100 days" fi
Another is to use GNU date to do the math:
# collect both times in seconds-since-the-epoch hundred_days_ago=$(date -d 'now - 100 days' +%s) file_time=$(date -r "$filename" +%s) # ...and then just use integer math: if (( file_time <= hundred_days_ago )); then echo "$filename is older than 100 days" fi
If you have GNU stat, you can ask for a file's timestamp in seconds-since-epoch, and do some math yourself (though this will potentially be a bit off on the boundary cases, since it's counting seconds -- and not taking into account leap days and such -- and not rounding to the beginning of a day):
file_time=$(stat --format='%Y' "$filename") current_time=$(( date +%s )) if (( file_time < ( current_time - ( 60 * 60 * 24 * 100 ) ) )); then echo "$filename is older than 100 days" fi
Another option, if you need to support non-GNU platforms, is to shell out to Perl (which I'll leave it to others to demonstrate).
If you're interested more generally in getting timestamp information from files, and portability and robustness constraints surrounding same, see also BashFAQ #87.
I'm surprised no one mentioned this method - it's hiding right there in man test
, implied by -nt
and -ot
, so I suspect it's been there for a long time:
N_DAYS_AGO=/tmp/n-days-ago.$$ touch -d "$N days ago" $N_DAYS_AGO if [ "$myfile" -ot "$N_DAYS_AGO" ]; then ... fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With