12

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.

5 Answers 5

13

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.

2
  • Damn, 36 seconds too slow. ;-)
    – htorque
    Oct 17, 2011 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, 2011 at 19:06
4

Running the command

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

gives this as the output:

myfilename-21-02-2014
3
  • Actually this will print myfilename-date +%d-%m-%Y.
    – Adaephon
    Feb 21, 2014 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 Feb 21, 2014 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, 2014 at 6:25
2

One of the possible soultions:

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

creates log111017

0

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.

0

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

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

date=time.gmtime()
month = str(date.tm_mon).zfill(2)
day=str(date.tm_mday).zfill(2)
year=str(date.tm_year)[-2:]
fname = 'log' + month + day + year

with open(fname,'a') as f:
    os.utime(fname,None) 

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*
$ ./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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .