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.

Melebius
  • 11,121
  • 8
  • 50
  • 77
Louis B.
  • 235
  • 1
  • 4
  • 9

5 Answers5

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.

Florian Diesch
  • 86,013
  • 17
  • 224
  • 214
4

Running the command

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

gives this as the output:

myfilename-21-02-2014
Eliah Kagan
  • 116,445
  • 54
  • 318
  • 493
Sreedhar GS
  • 141
  • 2
  • Actually this will print `myfilename-date +%d-%m-%Y`. – Adaephon Feb 21 '14 at 06: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 06: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 06:25
1

One of the possible soultions:

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

creates log111017

Sergey
  • 43,339
  • 13
  • 106
  • 107
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.

Dason
  • 848
  • 12
  • 27
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

Sergiy Kolodyazhnyy
  • 103,293
  • 19
  • 273
  • 492