shell 脚本中的 YYYY-MM-DD 格式日期 [英] YYYY-MM-DD format date in shell script

查看:40
本文介绍了shell 脚本中的 YYYY-MM-DD 格式日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在我的 bash shell 脚本中使用 $(date),但是,我想要 YYYY-MM-DD 格式的日期.
我如何得到这个?

I tried using $(date) in my bash shell script, however, I want the date in YYYY-MM-DD format.
How do I get this?

推荐答案

在 bash (>=4.2) 中,最好使用 printf 的内置日期格式化程序(bash 的一部分)而不是外部 date(通常是 GNU 日期).

In bash (>=4.2) it is preferable to use printf's built-in date formatter (part of bash) rather than the external date (usually GNU date).

因此:

# put current date as yyyy-mm-dd in $date
# -1 -> explicit current date, bash >=4.3 defaults to current time if not provided
# -2 -> start time for shell
printf -v date '%(%Y-%m-%d)T
' -1 

# put current date as yyyy-mm-dd HH:MM:SS in $date
printf -v date '%(%Y-%m-%d %H:%M:%S)T
' -1 

# to print directly remove -v flag, as such:
printf '%(%Y-%m-%d)T
' -1
# -> current date printed to terminal

在 bash (<4.2) 中:

In bash (<4.2):

# put current date as yyyy-mm-dd in $date
date=$(date '+%Y-%m-%d')

# put current date as yyyy-mm-dd HH:MM:SS in $date
date=$(date '+%Y-%m-%d %H:%M:%S')

# print current date directly
echo $(date '+%Y-%m-%d')

其他可用的日期格式可以从 日期手册页(用于外部非 bash 特定命令):

Other available date formats can be viewed from the date man pages (for external non-bash specific command):

man date

这篇关于shell 脚本中的 YYYY-MM-DD 格式日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆