I am trying to write a script that finds files that are from before September 24th, 2014, and deletes them. How would I do this?
Create a dummy file with time set to Sept. 24 2014 00:00h, then find anything NOT newer and delete:
#date format YYYYMMDDhhmm touch -t 201409240000 dateref find -type f ! -newer dateref -delete
Please make yourself a bit familiar with
find before using the
-delete option. Note that is must be on the last position and maybe check the results without
You can use
-newer option with (a reference file which has that date), along with
! to negate the -newer. You can use
touch -d to create the reference file. For example:
touch -d "2014-09-23 23:59:59.999999999" /tmp/reference-file find /path/to/directory/ ! -newer /tmp/reference-file -ls
You will probably want to pipe that into
less or redirect to a file for examination.
-ls option to
-delete after you've confirmed that it will only delete files you want deleted.
(if you don't mind also deleting files that were created exactly at midnight on 2014-09-14, you can just use
touch -d 2014-09-24 - because
! -newer doesn't just mean "older than", it means "older than or equal to". The .999999999 is probably "good enough" for most purposes)
Note: the above assumes GNU versions of both
touch. May or may not work with other versions. If you're using Linux, GNU utils are standard (unless you're using some tiny distro that uses
busybox or similar to save space).
Time of the last data modification of the current file is more recent than that of the last data modification of the reference file. If reference is a symbolic link and the
-Hoption or the
-Loption is in effect, then the time of the last data modification of the file it points to is always used.
-anewer in the same man page if you want to use access times rather than modification time.
-newerXY options are also relevant:
Succeeds if timestamp X of the file being considered is newer than timestamp Y of the file reference. The letters X and Y can be any of the following letters:
a The access time of the file reference B The birth time of the file reference c The inode status change time of reference m The modification time of the file reference t reference is interpreted directly as a time
Some combinations are invalid; for example, it is invalid for
t. Some combinations are not implemented on all systems; for example
Bis not supported on all systems. If an invalid or unsupported combination of
XYis specified, a fatal error results.
Time specifications are interpreted as for the argument to the
-doption of GNU
If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal error message results.
If you specify a test which refers to the birth time of files being examined, this test will fail for any files where the birth time is unknown.