Exercise
Backing Up Documents Nightly Exercise
Task
Back up your documents every night at 2 a.m., with each run writing to its own timestamped directory so one backup never overwrites another. Prove the schedule works before you trust it.
- Host
servera- Back up
/home/student/Documents- Destination
-
a timestamped directory under
/tmp - Schedule
- every night at 2 a.m.
-
Create something worth backing up
Build a small document tree so the backup has real files to copy, including one in a subdirectory.
mkdir -p ~/Documents/notes echo "Kernel panic on servera, 03:14" > ~/Documents/incident_report.txt echo "Check disk usage weekly" > ~/Documents/notes/reminders.txt ls -R ~/Documents -
Build and test the backup command
Check what the timestamp looks like, then run the backup by hand. Getting the command right at the prompt first is far easier than debugging it from a crontab.
date --iso-8601=minutes cp -r ~/Documents /tmp/documents_$(date --iso-8601=minutes) ls -d /tmp/documents_* -
Schedule it one minute from now
A nightly job is hard to test, so schedule it every minute first. Open your crontab and add the entry.
crontab -ePress i to enter insert mode and type the line. Use the absolute path, because cron does not expand
~the way your login shell does.* * * * * cp -r /home/student/Documents /tmp/documents_$(date --iso-8601=minutes)Press Esc to leave insert mode, then type
:wqto save. Read the crontab back to confirm it was accepted.crontab -l -
Confirm it ran
Wait for the next minute to tick over, then read the cron log.
sudo less /var/log/cronPress G to jump to the end and q to quit. Look for a matching pair of lines:
CROND[11611]: (student) CMD (cp -r /home/student/Documents /tmp/documents_$(date --iso-8601=minutes)) CROND[11609]: (student) CMDEND (cp -r /home/student/Documents /tmp/documents_$(date --iso-8601=minutes))Then look for a second backup directory.
ls -d /tmp/documents_* -
Set the real schedule
The command works, so give it the schedule you actually want. Open the crontab again.
crontab -ePress C to replace the whole line, and type the nightly version.
0 2 * * * cp -r /home/student/Documents /tmp/documents_$(date --iso-8601=minutes)Leave insert mode with Esc, save with
:wq, and read it back.crontab -l0 2 * * *is minute 0 of hour 2, every day of the month, every month, every day of the week. -
Clean up
Remove the schedule, then the files it produced.
crontab -r crontab -l rm -rf /tmp/documents_* ~/Documents