Reputation: 80
This is my script
#!/bin/bash
EXPIRYTIME=30
dateformat=(date -d \"+ $EXPIRYTIME minutes\" +"%Y-%m-%dT%H-%M-%S+00:00")
#dateformat=(date + "%Y-%m-%dT%H-%M-%S+00:00")
expiry=$(eval $dateformat)
And it is showing wrong results, that is Fri Aug 14 14:36:17 IST 2020\
But when I run in my cli it is showing right format that is: 2020-08-14T15-03-52+00:00
Can anyone help me in this?
Upvotes: 0
Views: 315
Reputation: 34334
The main problem is with this line:
dateformat=(date -d \"+ $EXPIRYTIME minutes\" +"%Y-%m-%dT%H-%M-%S+00:00")
where the =(...)
says to assign an array of values to the dateformat
variable.
Then eval $dateformat
fails to provide an array subscript so bash will use whatever value is assigned to index=0 which in this case is date
; net result is that you end up running date
(with no args) and you get the current date/time.
You have a couple options:
1 - continue to use the array but make sure you reference the entire set of array indices:
$ dateformat=(date -d \"+ $EXPIRYTIME minutes\" +"%Y-%m-%dT%H-%M-%S+00:00")
$ eval "${dateformat[@]}"
2020-08-14T04-53-55+00:00
2 - define the variable as a single string:
$ dateformat='date -d "+ '"${EXPIRYTIME}"' minutes" +"%Y-%m-%dT%H-%M-%S+00:00"'
$ eval "${dateformat}"
2020-08-14T04-53-57+00:00
Keep in mind for this particular case there's no need for the eval
as ${EXPIRYTIME}
can be fed directly to the date
command:
$ date -d "+ ${EXPIRYTIME} minutes" +"%Y-%m-%dT%H-%M-%S+00:00"
2020-08-14T04-53-58+00:00
NOTE: The above examples were run when local system time was Fri Aug 14 04:23:55 CDT 2020
Upvotes: 1