Shell Scripting: Creating report/log file names with date in filename

by nixcraft · 8 comments

When you write a shell scripts you need to create filename with date in it. For example instead of log file name "secure.log", you can create a filename called "secure-jan-02-06.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:
Sun Feb 5 18:23:44 IST 2006

To display date in MONTH-DAY-YEAR format you need to use date command as follows:
$ date +"%b-%d-%y"

Feb-05-06

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.

Featured Articles:

Want to read Linux tips and tricks, but don't have time to check our blog everyday? Subscribe to our daily email newsletter to make sure you don't miss a single tip/tricks. Subscribe to our weekly newsletter here!

{ 8 comments… read them below or add one }

1 andreyev 06.14.06 at 6:21 pm

IMHU, to see a sorted list of log files the best date options is “+%Y%m%d%H%M%S”. Separate fields with hyphen could make it more human readable.

When a lot of instances of your program is running simultaneously, may you should add the PID to this string.

2 Kate Ward 01.18.07 at 8:15 pm

Take a look at log4sh [http://log4sh.sourceforge.net/] as well. It might be a better choice for your logging needs.

3 Aaron 10.08.07 at 6:44 pm

Awesome stuff, you have save me tons of time

4 Itpatil 05.13.08 at 5:19 pm

Thank you. Very helpful.

5 Phil 05.16.08 at 1:10 pm

Okay, but how do I retrieve and format YESTERDAY’s date? Or, more generally, how do I perform date “arithmetic” from a shell script (adding days / weeks, etc)?

6 vivek 05.16.08 at 1:16 pm

Phil,

Try yest

7 Spenser 01.02.10 at 4:28 pm

Exactly what I needed. Thanks!

8 richa 03.11.10 at 6:09 am

very nice and helpful…thanks

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Previous post:

Next post: