Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

KSH Leap Year Calculation

Status
Not open for further replies.

SamBones

Programmer
Aug 8, 2002
3,186
US
OK, OK, I know it's been beaten to death, but I came up with a cool way to test for leap year in Korn Shell.

Code:
#!/bin/ksh

typeset -i IS_LEAP=$( cal 2 $(date '+%Y') | grep 29 | wc -l )

(( IS_LEAP )) && print "This is a leap year!"

if (( ! IS_LEAP ))
then
    print "NOT a leap year!"
fi

Basically it uses '[tt]cal[/tt]' to get a calendar of February of this year (simple mod to get other years), [tt]grep[/tt]s that one month calendar for a '29', then counts how many rows the grep output. If it's a leap year, IS_LEAP will equal 1. If it's not a leap year, IS_LEAP will be a 0. So IS_LEAP can be used as a boolean as in the example code.

 
hi,

there's not much of "kshisms".
this almost could be (arithmetic evaluation excepted, and variable's typing that is not essential) a POSIX script as well.

the script is fine, not the title of the subject.
 
Nice, but it will fail in 13 years. Put a tail between cal and grep to get rid of the year in the header that may cause problems.
 
daPeach: Yup, you're correct.

stefanhei: Good point. Didn't think it through I guess.

Code:
#!/bin/ksh

typeset -i IS_LEAP=$( cal 2 $(date '+%Y') | tail -2 | grep 29 | wc -l )

(( IS_LEAP )) && print "This is a leap year!"

if (( ! IS_LEAP ))
then
    print "NOT a leap year!"
fi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top