How to compare those (date) values in bash

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!

1 Answer

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 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like