invalid date error in the date command linux

2019-07-22 04:08发布

In the script I am using the command

CURRENT_DATE_tmp=`date -d $CURRENT_DATE +%Y%m%d`.

It gives error date: invalid date `+%Y%m%d' what may be the reason. I know that the variable CURRENT_DATE have value in it.

标签: linux shell date
3条回答
来,给爷笑一个
2楼-- · 2019-07-22 04:14

This is happening because the variable is unset or empty, and you did not quote the variable:

$ CURRENT_DATE=""
$ CURRENT_DATE_tmp=$(date -d $CURRENT_DATE +%Y%m%d)
date: invalid date ‘+%Y%m%d’

If you use quotes, no error:

$ CURRENT_DATE_tmp=$(date -d "$CURRENT_DATE" +%Y%m%d)
$ echo $CURRENT_DATE_tmp
20140704
查看更多
闹够了就滚
3楼-- · 2019-07-22 04:25

This has already been mentioned in a comment, but you must make sure there is actually a value in the variable $CURRENT if you want to do what you are trying to do. Try inserting these two lines in your script:

echo date is =$CURRENT=
date -d "$CURRENT" "+%Y%m%d"

If one of the lines of output appears like the one below, then you have neglected to set $CURRENT to a non-empty string:

date is ==

Trying various variations of date -d "$CURRENT" "+%Y%m%d" (with or without quotes, with or without space after -d) when $CURRENT is an empty string, either I see the "invalid date" error or I get today's date.

查看更多
家丑人穷心不美
4楼-- · 2019-07-22 04:31

date -d $CURRENT_DATE will print the date corresponding to the $CURRENT_DATE variable.

$) CURRENT_DATE="20140220"
$) date -d $CURRENT_DATE
Thu Feb 20 00:00:00 IST 2014

To store the date into a variable, try using

$) CURRENT_DATE_TMP=`date +%Y%m%d`
$) echo $CURRENT_DATE_TMP
20140704

EDIT

To print an existing date into a new format, use

$ CURRENT_DATE=`date +%Y-%m-%d`
$ echo $CURRENT_DATE 
2014-07-04
$ date -d$CURRENT_DATE "+%Y%m%d"
20140704

Better still, wrap the $CURRENT_DATE variable within quotes, so that dates with spaces don't break anything.

$ CURRENT_DATE=`date`
$ echo $CURRENT_DATE 
Fri Jul 4 17:59:45 IST 2014
$ date -d"$CURRENT_DATE" "+%Y%m%d"
20140704
$ date -d$CURRENT_DATE "+%Y%m%d"
date: extra operand ‘4’

In your current example, you have a space after the -d flag, remove it.

查看更多
登录 后发表回答