How to read date from terminal and compare with cu

2019-05-28 13:19发布

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!

3条回答
冷血范
2楼-- · 2019-05-28 13:32

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
查看更多
姐就是有狂的资本
3楼-- · 2019-05-28 13:41

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.

查看更多
三岁会撩人
4楼-- · 2019-05-28 13:55

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

查看更多
登录 后发表回答