Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a bash string into a date?

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:

  • capture and collect the date/time string in the file from the "other" server
  • read the string in the file
  • compare that date/time in the string with the current date/time
  • output something like "This event processed 12 minutes ago"

Any ideas? Thanks.

like image 842
Claude Lag Avatar asked Mar 17 '23 16:03

Claude Lag


1 Answers

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.

like image 89
fedorqui 'SO stop harming' Avatar answered Mar 20 '23 04:03

fedorqui 'SO stop harming'