Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

#1
December 31st, 2012, 02:11 PM
 Garrett85
Registered User

Join Date: Mar 2006
Posts: 21
Time spent in forums: 2 h 42 m 15 sec
Reputation Power: 0
Shell script to get leap year

In the program below I'M trying to use math in an if/else statement that's in a function to determine if it is or is not leap year. Please help I can't figure out what I'M doing wrong here.

#! /bin/bash

leap_year()
{
if [ \$((expr 0 -eq (\${YY} % 4))) ] && [ \$((expr 0 -ne (\${YY} % 100))) ]; then
echo "Leap Year"
else
echo "Not leap Year"
fi
}

leap_year \$YY

#2
December 31st, 2012, 05:35 PM
 SimonJM
Contributing User

Join Date: Mar 2006
Posts: 2,108
Time spent in forums: 1 Month 1 Week 1 Day 4 h 16 m 23 sec
Reputation Power: 1485
That should work for centuries, but not for general leap years. The process is it's a leap year if the year is exactly divisible by 4, unless it's a century where the year has to be eaxctly divisible by 100.
Either 'double-up' the tests, or do a bit more work and check for a century year beforehand, setting divisor to 400 or 4, depending on result, then use that to check the year.

Failing that, try:

Code:
```if [ \$(cal Feb \$YY | tail -n +3 | wc -w) -eq 29 ]
then
echo "\$YY is a leap year"
else
echo "\$YY not a leap year"
fi```
__________________
The moon on the one hand, the dawn on the other:
The moon is my sister, the dawn is my brother.
The moon on my left and the dawn on my right.
My brother, good morning: my sister, good night.
-- Hilaire Belloc

 Viewing: Dev Shed Forums > Operating Systems > Linux Help > Shell script to get leap year