2009-05-06

How to print date suitable for file name assignment

In bash script, it is common to name files with date part of it.




e.g.
system-20080808.zip, mysql-20070707.tar.gz, somelog-20090101.tar.bz2 and etc ...

Reason to name it in such a ways is easier to clean up the backup later, using bash script. If you have not notice, when listing of the files and sort it by name, it is automatically sorted by name  then date, which makes it scripting friendly. Here is some examples of how to print date suitable for file name assignment :

To get the date in the format of YYYYMMDD, use
date +%Y%m%d

Which :

%Y = the 4 digit year

%m = the 2 digit month

%d = the 2 digit day


Now we are ready to assign the date to the file name.
e.g. :
tar zcf /some/directory/compressedlog-$(date +%Y%m%d).tar.gz
ls >> filelisting-$(date +%Y%m%d).txt


If the date assignment is going to use for more then 1 time, assign it to a variable so that we don't have to type it again and again :
<start of script>
#!/bin/bash
CURRENTDATE=$(date +%Y%m%d)

:
:
:

grep search-term from-some-file >> output-$CURRENTDATE..txt

ifconfig >> NICdetails-$CURRENTDATE.txt

:
:
:

<end of script>

Namaste !!!

No comments: