0

I am running the following script, which has a function intended to tell me whether one date is before another, as seen at the very bottom of the script.

Now, the script has a few bugs. But one of them in particular is strange. The script creates files named by the dates that are inputted by the last argument.

It creates files called "09", "12", and "2015". Why are these files created? Here's the function. You'll notice the last few lines which call the function with inputs

function compare_two {
if [ $1 < $2 ];
then
        return 2
elif [ $1 > $2 ];
then
        return 3
else
        return 4
fi
}


function compare_dates {
# two input arguments:
# e.g.  2015-09-17 2011-9-18

date1=$1
date2=$2

IFS="-"


test=( $date1 )
Y1=${test[0]}
M1=${test[1]}
D1=${test[2]}

test=( $date2 )
Y2=${test[0]}
M2=${test[1]}
D2=${test[2]}

compare_two $Y1 $Y2
if [ $? == 2 ];
then
        echo "returning 2"
        return 2
elif [ $? == 3 ];
then
        return 3
else
        compare_two $M1 $M2;
        if [ $? == 2 ];
        then
                echo "returning 2"
                return 2
        elif [ $? == 3 ];
        then
                return 3
        else
                compare_two $D1 $D2;
                if [ $? == 2 ];
                then
                        echo $?
                        echo "return 2"
                        return 2
                elif [ $? == 3 ];
                then
                        echo "returning 3"
                        return 3
                else
                        return 4
                fi
        fi
fi
}

compare_dates 2015-09-17 2015-09-12
echo $?

the result doesn't throw an error, but rather outputs

returning 2
2

The result is incorrect, I'm aware. But I'll fix that later. What is creating these files and how do I stop it? Thanks.

makansij
  • 9,303
  • 37
  • 105
  • 183

2 Answers2

2

the lower and greater sign are interpreted as redirections. type man test and find out the right syntax

Baroudi Safwen
  • 803
  • 6
  • 17
0

Your problem is with the [ $1 < $2 ], the < is being understood as a redirection character.

The solution is to use any of this alternatives:

[ $1 \< $2 ]
[ $1 -lt $2 ]
(( $1 < $2 ))                     # works in bash.

The [[ $1 < $2 ]] is NOT an integer compare, but (from the manual):

« the < and > operators sort lexicographically using the current locale »

I'll recommend to use the (( $1 < $2 )) option.

to avoid a problem that some numbers (the ones that start with a zero) like 08 cause a problem when compared in an arithmetic expansion, use:

(( 10#$1 < 10#$2 ))
(( 10#$1 > 10#$2 ))

to force a base 10 for the numbers.

However, if possible, using GNU date is a lot easier IMhO (it transform Year/Month/Day into one single number to compare: seconds since epoch):

a=$(date -d '2015-09-17' '+%s');
b=$(date -d '2015-09-12' '+%s');
compare_two "$a"  "$b"