小编典典

shell脚本中的YYYY-MM-DD格式日期

all

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


阅读 193

收藏
2022-02-25

共1个答案

小编典典

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

因此:

# 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\n' -1

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

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

在 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 特定命令):

man date
2022-02-25