About nixCraft

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

Posted by Vivek Gite [Last updated: February 27, 2007]

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:

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.

Want to stay up to date with the latest Linux tips, news and announcements? Subscribe to our free e-mail newsletter or RSS feed to get all updates. You can Email this page to a friend.

You may also be interested in other helpful articles:

Discussion on This Article:

  1. andreyev Says:

    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 Says:

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

  3. Aaron Says:

    Awesome stuff, you have save me tons of time

  4. Itpatil Says:

    Thank you. Very helpful.

  5. Phil Says:

    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 Says:

    Phil,

    Try yest

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

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

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.