Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Is there a way to compare dates in bash or ksh?

597 views
Skip to first unread message

bolta...@yahoo.co.uk

unread,
Mar 3, 2009, 4:45:43 AM3/3/09
to
Hi

Is there a way to compare date strings , eg 20090302 , in shell
without having to resort to perl? I'm not talking about comparing file
dates.

Thanks for any help

B2003

Bjarni Juliusson

unread,
Mar 3, 2009, 5:42:35 AM3/3/09
to
bolta...@yahoo.co.uk wrote:
> Hi
>
> Is there a way to compare date strings , eg 20090302 , in shell
> without having to resort to perl? I'm not talking about comparing file
> dates.

They can be treated as numbers if they're in the format you gave above...

if [ $date1 -lt $date2 ]; then whatever; fi


Bjarni
--

INFORMATION WANTS TO BE FREE

bolta...@yahoo.co.uk

unread,
Mar 3, 2009, 7:26:01 AM3/3/09
to
On Mar 3, 10:42 am, Bjarni Juliusson <bja...@update.uu.se> wrote:

> boltar2...@yahoo.co.uk wrote:
> > Hi
>
> > Is there a way to compare date strings , eg 20090302 , in shell
> > without having to resort to perl? I'm not talking about comparing file
> > dates.
>
> They can be treated as numbers if they're in the format you gave above...
>
>    if [ $date1 -lt $date2 ]; then whatever; fi

Sorry , bad example. The format could be anything , eg 02Jan2009

B2003

Ben Bacarisse

unread,
Mar 3, 2009, 8:02:51 AM3/3/09
to
bolta...@yahoo.co.uk writes:

If you seriously mean "anything" then I am surprised that Perl can do
it! If you can live with those formats accepted by the data command
you can use

date --date=02Jan2009 +%Y%m%d

(I'd turn this into a shell function to give the date in the desired
canonical form.)

BTW. You don't need to compare as numbers. Formats like +%Y%m%d and
the more readable +%Y-%m-%d also compare correctly as strings.

--
Ben.

bolta...@yahoo.co.uk

unread,
Mar 3, 2009, 9:13:17 AM3/3/09
to
On Mar 3, 1:02 pm, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
> BTW.  You don't need to compare as numbers.  Formats like +%Y%m%d and
> the more readable +%Y-%m-%d also compare correctly as strings.

But strings can only be compared as equals or not equals , you can't
do > or < in shell can you?

B2003


Ben Bacarisse

unread,
Mar 3, 2009, 2:21:49 PM3/3/09
to
bolta...@yahoo.co.uk writes:

Your subject line references bash. bash has

[[ str1 < str2 ]]

along with > as well. The built-in version of test also supports the
< and > operators (but make sure you quote them!).

--
Ben.

Stephane CHAZELAS

unread,
Mar 4, 2009, 12:55:56 PM3/4/09
to
2009-03-03, 19:21(+00), Ben Bacarisse:

And portably you could use expr or awk. But for both, you should
do:

expr "x$a" "<" "x$b" > /dev/null
awk 'BEGIN {exit(!(ARGV[1] < ARGV[2]))}' "x$a" "x$b"

to force litteral comparison (and avoid problems with some
values of $a/$b with expr).

--
Stéphane

0 new messages