Sorin Buturugeanu
Sorin Buturugeanu

Reputation: 1122

OS X terminal command to create a file named on current date

I have set up a cron task and I want to save the output to a file. The file should have the name based on the time at which the cron was executed (eg.: 20110317-113051.txt).

My actual cron command is as follows:

lynx -dump http://somesite/script.php > /Volumes/dev0/textfile.txt

I want the textfile to be replaced by some sort of unique time stamp.

I've tried

lynx -dump http://somesite/script.php > $(date).txt
but I receive an error that the command is ambiguous.

Thanks for your help!

Sorin

Upvotes: 12

Views: 18217

Answers (2)

Gareth McCaughan
Gareth McCaughan

Reputation: 19981

The date command can be given a format to determine exactly what form it generates dates in. It looks as if you want $(date +%Y%m%d-%H%M%S).txt. With this format, the output of date should be free of spaces, parentheses, etc., which might otherwise confuse the shell or the lynx command.

See http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/date.1.html for documentation of the date command and http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strftime.3.html for documentation of the format string, which is the same as for the strftime function in the standard library.

Upvotes: 18

Paul R
Paul R

Reputation: 213060

You need to quote the file name, since date by default will have special characters in it:

lynx -dump http://somesite/script.php > "$(date).txt"

As @Gareth says though, you should specify a format string for date, so that you get a more readable/manageable file name, e.g.

lynx -dump http://somesite/script.php > "$(date +%Y%m%d-%H%M%S).txt"

Upvotes: 15

Related Questions