[NTLUG:Discuss] cop files with dynamic prefix
ntlug at thorshammer.org
ntlug at thorshammer.org
Tue Dec 19 14:26:59 CST 2006
I had to write a script to do just this, so I'll share what I found and some of my own comments.
> 1. copy all files and sub directories in myfolder to backup directory
For backups, you will not only want to copy the contents of the file, but the permissions, ownership, and maybe even access/change/mod times. There are commands that do this (cpio) and options to commands that do this (cp -a). For the command options, it depends on the platform(s) you will run this on, so do a man on the command on the platform to make sure it has the needed options.
> 2. create a directory under backup and automatically add date as prefix
There are many ways to do write the date. IMHO, the best is using YYYYMMDD where YYYY is the full year (2006 not 06), MM is the zero-padded month (01, 02, ..., 11, 12) and DD is the zero-padded day. So the date for today would be 20061219.
The cool thing about this date format is that if you sort a list of such dates numerically you will also sort it chronologically. Notice that 20061219 is also a number: 20,061,219. The "number" for yesterday, 20061218, is 20,061,218. It is smaller than the number for today, so sorting the dates numerically has the side effect of sorting them in time as well.
To get the date in that format you can use:
$ date '+%Y%m%d'
20061219
$
> 3. copy all files and sub directories in myfolder to newcreated directory
A problem when moving a directory with a date in it is that you need to find the date for "yesterday" (or you need to find "yesterday" on any day the script is run). Thankfully date makes finding the date for yesterday trivial:
$ date
Tue Dec 19 12:23:37 CST 2006
$ date -d '1 day ago'
Mon Dec 18 12:23:43 CST 2006
$
This also works with the format command:
$ date '+%Y%m%d'
20061219
$ date -d '1 day ago' '+%Y%m%d'
20061218
$
Robert Thompson
More information about the Discuss
mailing list