Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

bash - shell脚本中的YYYY-MM-DD格式日期(YYYY-MM-DD format date in shell script)

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

(我尝试在我的bash shell脚本中使用$(date) ,但我希望日期为YYYY-MM-DD格式。)

How do I get this?

(我怎么得到这个?)

  ask by Kapsh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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).

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

As such:

(因此:)

# 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

In bash (<4.2):

(在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')

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

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

man date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...