How can i make my cron/script to generate a log filename with timestamp in it ?

Hello Friends,

I would like my script to display date timestamps in the file name for every script execution.

Below is the scenario: (just for testing purpose)
I scheduled a cron job, lets say it runs every 5 min and record/logs output in to a log file.

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /tmp/test/mytestscpt.sh > /tmp/test/logs/crnlog.log

Here what i wanted to do; instated of over writing or appending the output to an existing log file "crnlog.log"; i would like to create/have separate response/output log file with time stamp in its name.

I tried to make use of " date +%m_%d_%y-%H.%M.%S " ; but was not able to achieve it.

for example;

first run,
it should create
/tmp/test/logs/crnlog.01_14_15-12.00.45.log

after 5 min,
it should run and create
/tmp/test/logs/crnlog.01_14_15-12.05.45.log

another 5 min after that,
It should create
/tmp/test/logs/crnlog.01_14_15-12.10.45.log

And so on.

Could you please give me some idea to implement this?

Thank you.

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /tmp/test/mytestscpt.sh > /tmp/test/logs/crnlog-$(date +%Y-%m-%d-%H-%M-%S).log 

Dates in YYYY-MM-DD-HH-MM-SS order sort, compare, and match easily.

1 Like

@Corona688
Awesome. Thanks much for the prompt response. I really appreciate.
Initially i tried like below

/tmp/$"date +%m_%d_%y-%H.%M.%S".log

i was just doing trial and error. finally i got, what i was looking for in few seconds. that's great.

Thank you.

If by chance a yearly retention is wanted, you can simply leave out the years and seconds, and it will overwrite the logs after one year:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /tmp/test/mytestscpt.sh > /tmp/test/logs/crnlog-$(date +\%m-\%d-\%H-\%M).log

Alternatively, a separate cleanup process can be run from the same cron entry:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * find /tmp/test/logs -type f -name "crnlog-*.log" -mtime +365 -delete; /tmp/test/mytestscpt.sh > /tmp/test/logs/crnlog-$(date +\%Y-\%m-\%d-\%H-\%M-\%S).log
1 Like

Please don't ask technical questions in private messages.

I just remembered that % is special to cron, and must be escaped like \%.

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /tmp/test/mytestscpt.sh > /tmp/test/logs/crnlog-$(date +\%m-\%d-\%H-\%M).log
1 Like

am sorry. I will make a note of it. Thank you.