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:
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- 10 Greatest Open Source Software Of 2009
- My 10 UNIX Command Line Mistakes
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- Top 20 OpenSSH Server Best Security Practices
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Linux Video Editor Software
- Email this to a friend
- Download PDF version
- Printable version
- Comment RSS feed
- Last Updated: Feb/27/2007


{ 8 comments… read them below or add one }
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.
Take a look at log4sh [http://log4sh.sourceforge.net/] as well. It might be a better choice for your logging needs.
Awesome stuff, you have save me tons of time
Thank you. Very helpful.
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)?
Phil,
Try yest
Exactly what I needed. Thanks!
very nice and helpful…thanks