Shivam Agrawal Shivam Agrawal - 6 months ago 4x
Bash Question

using tee command to create time specific log files

I am using 'tee' command to redirect the log of my shell program into a file.

My requirement is to append the current date and time with the file name.

sh | tee logfile_$date.txt #sample command

Output Log File:

logfile_2013-08-22-14.txt #yyyy-mm-dd-hh format

How can i achieve it ?


Since date '+%Y-%m-%d-%H' returns a date of the type 2013-08-21-10 (year-month-day-hour), you can use the following:

sh | tee logfile_$(date '+%Y-%m-%d-%H').txt

For example, let's print hello and also store it in a file:

$ echo "hello" | tee logfile_$(date '+%Y-%m-%d-%H').txt
$ ls logfile_*

As you see, a file with the name logfile_2013-08-21-10.txt has been created at the same time that the string appeared in the screen.