1

I would like to get a shell command to find the files with a modification date for yesterday — 24 hours only. That means I would like to find the files which were modified yesterday only.

oguz ismail
  • 1
  • 16
  • 47
  • 69
devops
  • 173
  • 4
  • 16
  • Suppose you run the command at 10:00 on 2016-07-14. Are you looking for files modified between 2016-07-13T00:00:00 and 2016-07-13T23:59:59 (all in your current time zone)? Or are you looking for files modified in the last 24 hours, in which case the range is between 2016-06-13T10:00:00 and 2016-07-14T10:00:00? Or something else? – Jonathan Leffler Jul 14 '16 at 17:20

2 Answers2

4

Use find with mtime and daystart, it will find files modified 1*24 hours ago, starting calculations from midnight (daystart):

find dir -daystart -mtime 1
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
  • See [Explaining `find -mtime` command](http://stackoverflow.com/questions/25599094/explaining-find-mtime-command/25599430?s=1|4.3858#25599430) — I think that does not do what is required yet. – Jonathan Leffler Jul 14 '16 at 17:17
  • Right, but it will do the correct thing when combined with `-daystart` (that is find files from yesterday between 0:00 and 23:59) – Krzysztof Krasoń Jul 14 '16 at 18:45
  • Yup — `-daystart` works, assuming you are using GNU `find`. (BSD / Mac OS X `find` does not support `-daystart`, for example, even though it does support `-newermt` and related options.) – Jonathan Leffler Jul 14 '16 at 18:54
1

This answer assumes you have GNU date and find. It also assumes that if you run the script at any time on 2016-07-14, you want the files modified at or after 2016-07-13T00:00:00 and before 2016-07-14T00:00:00.

If those assumptions are correct, then you can use:

find .  -newermt "$(date -d yesterday +'%Y-%m-%d 00:00:00')" \
    '!' -newermt "$(date -d today     +'%Y-%m-%d 00:00:00')"

The first command substitution generates (on 2016-07-14) the output 2016-07-13 00:00:00 and the second 2016-07-14 00:00:00. The -d today is not needed to get the right result, but shows the symmetry.

The condition overall means 'modified at or after midnight yesterday morning and not modified since midnight this morning'.

It is harder to do this on systems without GNU date to evaluate the different dates.

See Explaining find -mtime command for information on why using -mtime will not meet the assumed requirements.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278