13

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,750
Louis B.
  • 245

5 Answers5

14

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.

4

Running the command

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

gives this as the output:

myfilename-21-02-2014
Eliah Kagan
  • 119,640
2

One of the possible soultions:

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

creates log111017

Sergey
  • 44,353
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
  • 858
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