How to compare two dates in a shell script?
For example something like
todate=2013-07-18 cond=2013-07-15 if [ $todate -ge $cond ]; then break fi
It doesn't work. How can I achieve the desired result?
You are missing the date format for the comparison:
You are missing looping structures too, how are you planning to get more dates?
This is not a problem of looping structures but of data types.
Those dates (
What you can do is use a different notation for your dates so that they are integers. For example:
will produce an integer like 20130715 for July 15th, 2013. Then you can compare your dates with "-ge" and equivalent operators.
Update: if your dates are given (e.g. you are reading them from a file in 2013-07-13 format) then you can preprocess them easily with tr.
dates are strings, not integers; you can't compare them with standard arithmetic operators.
one approach you can use, if the separator is guaranteed to be
This works as far back as
There is also this method from the article titled: Simple date and time calulation in BASH from unix.com.
These functions are an excerpt from a script in that thread!
If your script is a bash or ksh or zsh script, you can use the
In any shell, you can convert the strings to numbers while respecting the order of dates simply by removing the dashes.
Alternatively, you can go traditional and use the
As invoking subprocesses in a loop can be slow, you may prefer to do the transformation using shell string processing constructs.
Of course, if you can retrieve the dates without the hyphens in the first place, you'll be able to compare them with
Can use a standard string comparison to compare the chronological ordering [of strings in a year, month, day format].
Thankfully, when [strings that use the YYYY-MM-DD format] are sorted* in alphabetical order, they are also sorted* in chronological order.
(* - sorted or compared)
Nothing fancy needed in this case. yay!