如何在 (OS X) bash 中以 YYYY-MM-DD 格式获取当前日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6312872/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:37:57  来源:igfitidea点击:

How can I get the current date in YYYY-MM-DD format in (OS X) bash?

macosbash

提问by Alan H.

Writing a shell script and I want to do something like this:

编写一个shell脚本,我想做这样的事情:

cp myfile.ext myfile.2011-06-10.ext

where 2011-06-10 is the current date.

其中 2011-06-10 是当前日期。

Thoughts?

想法?

回答by Nemo

cp myfile.ext myfile.`date +%Y-%m-%d`.ext

回答by Dirk Eddelbuettel

Try

尝试

 cp myfile.ext myfile.`date "+%Y-%m-%d"`.ext

and for a proper solution, decompose the name first into basename and extension, assign the date and then reassemble for final targetname.

对于正确的解决方案,首先将名称分解为基本名称和扩展名,分配日期,然后重新组合为最终目标名称。

The key is that

关键是

 date +FORMAT

allows for very rich format strings. See date --helpor the rather fine manual.

允许非常丰富的格式字符串。请参阅date --help或相当不错的手册。

回答by dreamlax

The man pagefor the dateutility contains examples of how to output the date in various ways.

手册页date实用程序包含如何输出以各种方式日期的例子。

回答by jm666

cp myfile.ext myfile.$(date +%F).ext