2

端末から日付を読み取り、シェルスクリプトを使って現在の日付と比較する適切な方法を知りたいのですが、

私は以下のスクリプトを持っています、

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 

期待どおりに実行されていません。私を助けてください。

アップデート

これが私の最終バージョンです。

#! /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

みんな、ありがとう!

4

3 に答える 3

4

高度な Bash スクリプト ガイドから:

7.3. その他の比較演算子

...

文字列比較

...

<
    is less than, in ASCII alphabetical order

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

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

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

だから、あなたの

   if [ $todate < $a ];then

になる

if [ $todate \< $a ];then

また

if [[ $todate < $a ]];then
于 2013-01-24T13:09:07.690 に答える
2

日付には+%s形式があります。

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

現在の日付を秒単位で保存します。次に、ユーザー入力の日付も秒に変換します。比較できますように。

于 2013-01-24T12:59:33.963 に答える
0

解決策は次のとおりです。

ここでこのソリューションでは、日付を単一の整数に変換していますが、日付が大きいほど常に現在の日付よりも大きい整数になることは明らかです

a=date +%Y%m%d

ながら[1]; 行う

echo "日付を入力してください" 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" 

終わり

于 2013-01-24T13:55:31.550 に答える