Friday, June 27, 2008

Shell Scripting: Using date within report/log file names

When you write a shell scripts you need to create filename with date in it. For example instead of log file name "traces.log", you can create a filename called "traces-Jun-27-8.log".

The date in file will make it easy to find out all logs or reports. You can display the current date and time in the given FORMAT using date command. If you just type date command it will display in standard FORMAT:

$ date
Output:
Fri Jun 27 11:43:25 IST 2008

To display date in MONTH-DAY-YEAR format you need to use date command as follows:

$ date +"%b-%d-%y"

Jun-27-08

As you can see I have used FORMAT as follows

date +"FORMAT"

Where, FORMAT can be any one of the following:

  • %a : Abbreviated weekday name (Sun..Sat)
  • %b : Abbreviated month name (Jan..Dec)
  • %B : Full month name, variable length (January..December)
  • %d : day of month (01..31)
  • %e : day of month, blank padded ( 1..31)
  • %H : 24 hour format (00..23)
  • %I : 12 hour format (01..12)
  • %j : day of year (001..366)

First obtained date:
$ NOW=$(date +"%b-%d-%y")

Create a file with date in filename
$ LOGFILE="log-$NOW.log"

Display filename:
$ echo $LOGFILE

You can use first two commands in script.

No comments: