My shell script for checking leap year is showing

2019-04-14 04:47发布

问题:

#!/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] 

回答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


回答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


回答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


标签: bash shell