My shell script for checking leap year is showing

2019-04-14 04:55发布

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

标签: bash shell
3条回答
仙女界的扛把子
2楼-- · 2019-04-14 05:27

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
查看更多
女痞
3楼-- · 2019-04-14 05:36

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
查看更多
在下西门庆
4楼-- · 2019-04-14 05:40

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
查看更多
登录 后发表回答