Using the command-line, I want to create a log file with today's date in the name (for example, today is 05/17/2011, so the filename would have to be log051711).

I know how to create the file (touch filename), but I don't know how to get today's date. I have looked at the manual for date, but it seems that I can't really format its output?

Any help would be appreciated.


You can format the output using the '+FORMAT' parameter, e.g.

touch "log$(date +'%m%d%y')"

See the manpage for what sequences you can use in FORMAT.

  • Damn, 36 seconds too slow. ;-) – htorque Oct 17 '11 at 12:03
  • 1
    I just figured out that to use this in a cron job, I had to escape the %-signs, so that it read: touch "log$(date +'\%m\%d\%y')" – Louis B. Oct 18 '11 at 19:06

Running the command

echo "myfilename-"`date +"%d-%m-%Y"`

gives this as the output:

  • Actually this will print myfilename-date +%d-%m-%Y. – Adaephon Feb 21 '14 at 6:03
  • True.. MyFileName is just a prefix.. If needed we can keep it, else.. echo date +"%d-%m-%Y" this is enough... it will print only date 21-02-2014 – Sreedhar GS Feb 21 '14 at 6:10
  • Ah, now I see: I got confused because the ` did not appear in your answer. This is because they are used by askubuntu to indicate code blocks. You should mark code by either surrounding it with backticks or by indenting the paragraph with the code with 4 spaces. For starters you probably should use the menu above the editor for that and check your post in the preview below the textbox before submitting. – Adaephon Feb 21 '14 at 6:25

One of the possible soultions:

date +log%y%m%d | xargs touch

creates log111017


I'm sure somebody else has a better way to do this but assuming you want month-day-year this should work:

touch log`date +%m%d%y`  

and you can reorder the %m, %d, %Y to reflect the ordering you want. The man page for date tells you more about additional formats.


Python can do this job as well. The small script for that would be the following:

#!/usr/bin/env python
import time,os

month = str(date.tm_mon).zfill(2)
fname = 'log' + month + day + year

with open(fname,'a') as f:

The idea here is simple: we use time.gmtime() to get current date, extract specific fields from the structure it returns, convert appropriate fields to strings, and create filename with the resulting name.

Test run:

$ ls
$ ./touch_log_file.py                                                                                             
$ ls
log010317  touch_log_file.py*

At the moment of writing it is January 3rd , 2017. Thus the resulting filename is appropriately month,day,year - log010317

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.