How to read date from terminal and compare with cu

2019-05-28 13:48发布

问题:

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!

回答1:

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


回答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.



回答3:

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