#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2006
    Posts
    58
    Rep Power
    9

    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

    read -p "Enter year" YY

    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. #2
  3. No Profile Picture
    Contributing User
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Mar 2006
    Posts
    2,439
    Rep Power
    1688
    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

IMN logo majestic logo threadwatch logo seochat tools logo