bash OS X 终端命令创建一个以当前日期命名的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5337262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
OS X terminal command to create a file named on current date
提问by Sorin Buturugeanu
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).
我已经设置了一个 cron 任务,我想将输出保存到一个文件中。该文件的名称应基于执行 cron 的时间(例如:20110317-113051.txt)。
My actual cron command is as follows:
我的实际 cron 命令如下:
lynx -dump http://somesite/script.php > /Volumes/dev0/textfile.txt
I want the textfileto be replaced by some sort of unique time stamp.
我希望textfile被某种独特的时间戳替换。
I've tried
我试过了
lynx -dump http://somesite/script.php > $(date).txt但我收到一个错误,指出命令不明确。
Thanks for your help!
谢谢你的帮助!
Sorin
索林
回答by Gareth McCaughan
The datecommand 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 dateshould be free of spaces, parentheses, etc., which might otherwise confuse the shell or the lynxcommand.
该date命令可以给出的格式,以确定到底是什么形式,它的产生日期。看起来,如果你想$(date +%Y%m%d-%H%M%S).txt。使用这种格式,输出date应该没有空格、括号等,否则可能会混淆 shell 或lynx命令。
See http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/date.1.htmlfor documentation of the datecommand and http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/strftime.3.htmlfor documentation of the format string, which is the same as for the strftimefunction in the standard library.
有关命令的文档,请参阅http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man1/date.1.htmldate和http://developer.apple.com/library/mac /#documentation/Darwin/Reference/ManPages/man3/strftime.3.html用于格式字符串的文档,strftime与标准库中的函数相同。
回答by Paul R
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.
正如@Gareth 所说,您应该为日期指定一个格式字符串,以便获得更易读/可管理的文件名,例如
lynx -dump http://somesite/script.php > "$(date +%Y%m%d-%H%M%S).txt"

