INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
• Talk With Other Members
• Be Notified Of Responses
• Keyword Search
Favorite Forums
• Automated Signatures
• Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

KSH Leap Year Calculation

KSH Leap Year Calculation

(OP)
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 'cal' to get a calendar of February of this year (simple mod to get other years), greps 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.

RE: KSH Leap Year Calculation

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.

RE: KSH Leap Year Calculation

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.

RE: KSH Leap Year Calculation

(OP)
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 

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

• Talk To Other Members
• Notification Of Responses To Questions
• Favorite Forums One Click Access
• Keyword Search Of All Posts, And More...

Register now while it's still free!