How to compare those (date) values in bash
15,930
Bash has its own testing syntax, where you can use >
and <
:
$ val1=2013-12-31T00:00:00
$ val2=2014-11-19T15:40:30
$ [[ $val1 > $val2 ]]
$ echo $?
1
$ [[ $val1 < $val2 ]]
$ echo $?
0
Alternatively you can use Unix timestamps and compare the integer values:
$ val1=$(date --date='2013-12-31T00:00:00' +%s)
$ val2=$(date --date='2014-11-19T15:40:30' +%s)
$ [ $val1 -gt $val2 ]
$ echo $?
1
$ [ $val1 -lt $val2 ]
$ echo $?
0
Related videos on Youtube
Author by
Michael Niemand
Updated on September 18, 2022Comments
-
Michael Niemand almost 2 years
I need to compare 2 strings of the following formatting:
2013-12-31T00:00:00 2014-11-19T15:40:30
Its a custom datetime format. I tried different things, none worked:
if [ ${val1} < ${val2} ] || [ ${val1} == ${val2} ]; then ...
or
if [ ${val1} <= ${val2} ]
or
if [[ ${val1} -el ${val2} ]]
Thanks guys!
-
Michael Niemand over 9 yearsthanks! I could have sworn, I tried something like this ... converting to int. But bash is pretty unforgiving when it comes to brackets, quotes and even whitespaces etc. Thanks again!