如何在linux中将变量设置为当前日期和日期1?

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

How to set a variable to current date and date-1 in linux?

linuxbashdate

提问by cloudbud

I want to set the variable date-todayto the current date, and date_dirto yesterday's date, both in the format yyyy-mm-dd.

我想将变量date-today设置为当前日期和date_dir昨天的日期,格式均为yyyy-mm-dd.

I am doing this:

我正在这样做:

#!/bin/bash
d=`date +%y%m%d%H%M%S`
echo $d

采纳答案by cloudbud

You can try:

你可以试试:

#!/bin/bash
d=$(date +%Y-%m-%d)
echo "$d"

EDIT: Changed y to Y for 4 digit date as per QuantumFool's comment.

编辑:根据 QuantumFool 的评论,将 4 位日期的 y 更改为 Y。

回答by ray

you should man datefirst

你应该man date

date +%Y-%m-%d
date +%Y-%m-%d -d yesterday

回答by fraff

simple:

简单的:

today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"

回答by xloto

You can also use the shorter format

您也可以使用较短的格式

From the man page:

从手册页:

%F     full date; same as %Y-%m-%d

Example:

例子:

#!/bin/bash
date_today=$(date +%F)
date_dir=$(date +%F -d yesterday)