I have a file which contains a string:
2014-11-22 08:15:00
... which represents Nov 22 2014 @ 8:15 AM
.
I want to parse this string and use it with the date function in BASH to compare with the current date. I have code that compares dates but both dates are generated by BASH and it's easy to format and compare. However, I can't use the string (which is collected from another system) to compare.
I've tried stuff like:
$ mydate=$(cat filewithstring);date -d $mydate
$ mydate=$(cat filewithstring);date -d '$mydate'
$ mydate=$(cat filewithstring);date -d $mydate "+%Y-%m-%d %H:%M:%S"
I end up with errors like:
date: the argument ‘08:00:00’ lacks a leading '+'; when using an option to specify date(s), any non-option argument must be a format string beginning with '+'*
...or...
date: extra operand ‘+%Y-%m-%d %H:%M:%S’
I know that if I type in the string explicitly, it works fine:
$ date -d '2014-11-22 08:15:00'
Sat Nov 22 08:15:00 EST 2014
In the end, I'm hoping to do the following:
Any ideas? Thanks.
This is because you are using single quotes, so that the value of the variable is not expanded.
You can say:
mydate=$(<filewithstring)
date -d"$mydate" "+%Y-%m-%d %H:%M:%S"
^ ^
Note also mydate=$(<filewithstring)
is a more optimal way to read the file into a variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With