'My shell script for checking leap year is showing error
#!/bin/bash
echo "Enter the year (YYYY)"
read year
if[ $((year % 4)) -eq 0]
then
if[ $((year % 100)) -eq 0]
then
if[ $((year % 400)) -eq 0]
then
echo "its a leap year"
else
echo "its not a leap year"
fi
else
echo "Its not a leap year"
fi
else
echo "its not a leap year"
fi
its showing error on 7th line and also on
[ $((year % 4)) -eq 0]
Solution 1:[1]
You've made it too complicated. Use this code to figure leap year:
isleap() {
year=$1
(( !(year % 4) && ( year % 100 || !(year % 400) ) )) &&
echo "leap year" || echo "not a leap"
}
Test it:
$ isleap 1900
not a leap
$ isleap 2000
leap year
$ isleap 2016
leap year
$ isleap 1800
not a leap
$ isleap 1600
leap year
Solution 2:[2]
You miss some blanks which are nesessary in bash:
echo "Enter the year (YYYY)"
read year
if [ $((year % 4)) -eq 0 ]
then
if [ $((year % 100)) -eq 0 ]
then
if [ $((year % 400)) -eq 0 ]
then
echo "its a leap year"
else
echo "its not a leap year"
fi
else
echo "Its a leap year"
fi
else
echo "its not a leap year"
fi
Solution 3:[3]
Test This Code:
#!/bin/bash
echo "Enter a year to check - "
read y
year=$y
ans=`expr $year % 4`
if [ $ans -eq 0 ]
then
echo "Leap Year"
else
echo "Not a Leap Year"
fi
Solution 4:[4]
I like one-liners because I do a lot of scripting. Here's an awk solution and test code:
#!/bin/csh -f
set years = "1898 1899 1900 1901 1902 1903 1904 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2016"
foreach year ($years) echo -n "$year " echo $year | awk '{if(($1%4)!=0){ly=0}else{if(($1%400)==0){ly=1}else{if(($1%100)==0){ly=0}else{ly=1}}}} END{if(ly){print "yes"}else{print "no"}}' end
The logic is elsewhere on this page
Solution 5:[5]
You can use this also
if [[ $(( y % 4 )) = 0 && $(( y % 400 )) = 0 || $(( y % 100)) != 0 ]]
or

Solution 6:[6]
#!/bin/bash
echo "Enter the year (YYYY)"
read year
if [ $((year%4)) -eq 0 ]
then
if [ $((year%100)) -eq 0 ]
then
if [ $((year%400)) -eq 0 ]
then
echo "its a leap year"
else
echo "its not a leap year"
fi
else
echo "Its a leap year"
fi
else
echo "its not a leap year"
fi
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anubhava |
| Solution 2 | |
| Solution 3 | Mazin Ibrahim |
| Solution 4 | Ed Christiansen |
| Solution 5 | cigien |
| Solution 6 | resh singh |
