0

Neither of these options seem to work. What am I doing wrong? (leapb, leapc and iyr are integer values)

if [[ $leapb -eq $iyr && $leapc -ne $iyr ]]; then
  leap=0
fi

Alternatively,

if [[ $leapb -eq $iyr ]] && [[ $leapc -ne $iyr ]]; then
  leap=0
fi

When running this using iyr=1979, leapb=1900, leapc=1600, the script doesn't reach the leap=0 line, with error msg stating -eq: unary operator expected .

Kusalananda
  • 333,661

2 Answers2

1

With a simplified version of your code:

[[ $a -eq $b ]]

There is no error with any value of a and b, even strings, empty, or unset.

An older version of [[ is [, but even that, properly quoted:

[ "$a" -eq "$b" ]

Only complains when the value inside a or b is an string (or empty/unset):

./script: line 13: [: StringInsideA: integer expression expected

Which means that the actual code you are testing is both using [ and not quoting the variable expansions (bad idea):

[ $a -eq $b ]

In which case, if a is empty/unset while b has some value (or viceversa) the error reported will be:

./script: line 14: [: -eq: unary operator expected

Conclusion: please use the [[ version of the test (while in bash,ksh,zsh).

logic

For the values you report:

Understand that if leapb=1900 and iyr=1979 (that is not equal) the first test fails and the leap=0 will never be executed no matter what the value of leapc might be.

The only way to get to execute leap=0 is that leapb=iyr and then leapc is not equal to iyr.

simpler

If all you want to do is to detect when a year is leap, use this:

leap=$(( y>0 && ( y%4==0 && y%100>0 || y%400==0 ) ))

In this formula, leap will be 1 for leap years and 0 otherwise.

0

I can't reproduce the error in bash given your code. With the given values, the code would not reach leap=0 since $iyr and $leapb are not equal.

However, if I modify it like this:

if [ $leapb -eq $iyr ] && [ $leapc -ne $iyr ]; then
    leap=0
fi

then this would produce

[: -eq: unary operator expected

if $leapb is an empty string.

With the [[ ... ]] syntax, the test would fail silently though.

Related reading:

Kusalananda
  • 333,661