Saturday, May 28, 2022

[SOLVED] Copying / Tarring Files that have been modified in the last 14 days

Issue

I have a server whose files are modified every so now and again.

We want to have a script or cron job that runs every 7 days and finds any php files that have been modified or created in the last 14 days and puts them in a tar or a zip file on the server so it can be downloaded.

This command finds the right files:

find . -name "*.php" -mtime -14 -print

What else do I need to do?


Solution

if your list of files from find output is correct just pipe it to tar:

find . -name "*.php" -mtime -14 -print | xargs tar cvf backup.tar

You should check tar options in man. You might want use for example -p (preserve permissions), just look for useful options in man and use whatever you need.

[Addendum] if your files might contain spaces or newlines, prefer the -print0 and xargs -0 to use null characters as separators:

find . -name "*.php" -mtime -14 -print0 | xargs -0 tar cvf backup.tar

and to add it to cron, the simplest way if your distro supports it, is to put your script in:

/etc/cron.weekly

otherwise you have to modfiy crontab:

crontab -e

and put there a line like:

0 3 * * 6 <user> <your script>

it runs a script at 3am every saturday, the last script is day of the week, 0 or 7 is sunday.

man 5 crontab:

 field          allowed values
          -----          --------------
          minute         0-59
          hour           0-23
          day of month   1-31
          month          1-12 (or names, see below)
          day of week    0-7 (0 or 7  is  Sun,  or  use
          names)


Answered By - aleksanderzak
Answer Checked By - Katrina (WPSolving Volunteer)