I want to tar a directory at a regular interval (say every morning at 4am) so I was planning on using crontab. How can I have the date be in the filename ie srcdirectorybackup5-30-09.tar so that I can differentiate between all of the tar files.
You want dates in ISO format - YYYY-MM-DD. They sort properly that way.
tar -cf srcdirectorybackup`date +%F`.tar /path/to/src
Assumes tar and date are in the path. You can add this line to a crontab.
Cripes! ericslaw is absolutely right. Those %'s need to be escaped if they're used in the crontab file or they'll be interpreted as newlines!
So, if you're going to put this line right into the crontab, escape the "%" with a "\".
tar -cf srcdirectorybackup`date +\%F`.tar /path/to/src
The rep really ought to go to ericslaw...
several folks have suggested the wonderful date +%Y%m%d_%H%M%S style solution but nobody has mentioned the major caveat of '%' in crontabs...
'%' it is equivalent to '\n' so your cronjob will likely fire and fail mystereously!
You'll more likely want to simply escape it with backslash like this (and I also like to get some kind of inventory or other output to check that it ran).
0 4 * * * tar vcf /path/to/dsttarfile.tar.`date +\%Y\%m\%d_\%H\%M\%S` /path/to/srcdir > /path/to/logfile.log 2>&1
You might consider using `date +%w' as part of your tarfile, so you have a tar file for each of the last 7 days and dont have to worry about purging old copies.
assuming you can handle the crontab stuff, for bash, the command would be as follows:
bash -c "tar -cf `date +%F`test.tar foo bar"
Of course, foo and bar are the files, test.tar is the rest of the suffix you want for the file, and you put in any option you need :)
This works in both cygwin and linux. I'm not familiar enough with cron to know if telling it which shell to use like that is necessary.
In many Linux distribution this are the steps you have to follow:
- cronttab -e
- On the text editor enter: 0 4 * * * /home/scripttaringsrc.sh
- exit the editor saving the files with ":wq"
The create the file /home/scripttaringsrc.sh
tar -cf srcdir 'date +%Y-%m-%d_%Hh%Mm'.tar /path/to/dst
Don't forget to chmod the scripttaringsrc.sh to execute permissions.
I have this little script that pack my entire etc dir and saves it in a directory with the correct date.
Save this script and put it in /etc/cron.daily/ (if that is available in your dist), since the scripts that is in that dir executes "ones per day" most often sometimes around 4. However a quick look in /etc/crontab will show the exact details.
#!/bin/sh date=`date +%Y%m%d-%H%M` #echo Tid: $date bpath=/var/backup/computername cd $bpath/ mkdir sys$date cd sys$date datumfil=$bpath/sys$date/$date > $datumfil tar -cvzf etc.tar.gz /etc/ > etc.tar.gz.list md5sum * > md5sum ls -lh >> md5sum
Note: you need to change this a little so you get the "correct" filename you wanted.