I know this is a common question, but I do not understand how the solutions provided work. Everyone advises to change the date to seconds from the epoch and then divide by (24 * 3600) to get the difference in days. Or use
if [ $first_date -gt $second_date ]
However, what I don't understand is why no one notices the glaring mistake of using seconds from epoch in that they would differ even within a day. Or if you consider 5:30 pm of a specific day and 9:00 am of the next day, the difference between the seconds won't lead to a gap of 24 hours, and thus, they would be erroneously considered to be the same day.
My usage scenario is this: I need to purge logs that are older than a given number of days. Thus, my expiration_date, which I am forming after taking the user input of the number of days is:
expiration_date=$(date -d "-$1 day" + %s)
My file modification dates I am getting by using stat command as follows:
file_date=$( stat -c %Y $entry )
I need to compare these two dates and purge them if the file modification dates are "lesser than" the expiration date. Please help me in this regard.
I am really confused as to the use of the mtime argument of the find command. Let's consider that we have the following files:
If I now run the find command using "0" as the mtime argument on Nov 19, it's giving me all the files except the first four.
find /dir/ -type f -mtime 0 -name "Nov*"
And if I run it using "+0", it's giving me only the first four files.
find /dir/ -type f -mtime +0 -name "Nov*"
If we express this using variables, saying that we want to purge logs from the nth day of the month and further back, and we run the command on the (n+1)th day using mtime as +0, which should translate to "1 day back and further", it's actually taking the files from the (n-1)th day and back, i.e. from "2 days back and further". Does this mean that there is no way to get just the files from 1 day back and further somehow? The argument of "0" is mixing it with today's files as well.
So I incorporated the
-daystart option as pointed out by @AdminBee, and results are as per my expectations. Now if I run the command on the (n+1)th day trying to remove the logs of the nth day and earlier, the command would be
find /dir/ -type f -daystart -mtime +0 -name "Nov*"
Irrespective of whether the file modification timestamp is within the 24-hour period moving back from now, it will now consider the files of the previous day as being behind by 1 day, and will also list all other files previous to them.