2

I want to know the appropriate way of reading date from terminal and comparing with current date using shell script,

I have the below script,

a=`date +%Y-%m-%d`
while [ 1 ] ; do
        echo "Enter Date"
    read todate
    if [ $todate < $a ];then
        break;
    fi
    echo "todate greater than curDate" 
done 

it is not running as expected. Please help me.

UPDATE

Here is my final version,

#! /bin/bash
DATE=$(date '+%s')
while [ 1 ] ; do
        echo "Enter Date[DD MM YYYY]:"    
    read D M Y
    THIS=$(date -d "$Y-$M-$D" '+%s')

    if (( THIS < DATE )) ; then
        break
    fi
done

Thanks everyone!

Anantha Krishnan
  • 3,068
  • 3
  • 27
  • 37

3 Answers3

4

from Advanced Bash-Scripting Guide:

7.3. Other Comparison Operators

...

string comparison

...

<
    is less than, in ASCII alphabetical order

    if [[ "$a" < "$b" ]]

    if [ "$a" \< "$b" ]

    Note that the "<" needs to be escaped within a [ ] construct.

So, your

   if [ $todate < $a ];then

becomes

if [ $todate \< $a ];then

or

if [[ $todate < $a ]];then
Alexey Shumkin
  • 409
  • 3
  • 8
  • Since not every `date` supports `%s` this is slightly more portable, with the caveat that you must always use YMD order and zero padding (i.e. `+%Y-%m-%d` as in the original questions). – mr.spuratic Jan 24 '13 at 13:29
  • Note that not all versions of `[` (nor all shells for which `[` is a builtin) will accept `<` as an operator. `bash`, and surprisingly `dash` accept `<`. `ksh` and `zsh` do not. – William Pursell Jan 24 '13 at 18:12
2

date has +%s format.

 %s     seconds since 1970-01-01 00:00:00 UTC

you save current date in second. Then convert user input date also in second. so you could compare.

Kent
  • 189,393
  • 32
  • 233
  • 301
0

Here is the solution:

Here in this solution i am converting dates to single integer and it is obvious that greater date will always be larger integer than current date

a=date +%Y%m%d

while [ 1 ] ; do

echo "Enter Date" read todate echo "$todate" > temp

for i in 1 2 3
    do 
      y=`cut -d- -f$i temp`
      x=$x$y
    done 
if [ $x -lt $a ];then
    exit;
fi
echo "todate greater than curDate" 

done

ASHU
  • 214
  • 2
  • 5