bash 我用于检查闰年的 shell 脚本显示错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32196628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:30:00  来源:igfitidea点击:

My shell script for checking leap year is showing error

bashshell

提问by Jens

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

它在第 7 行以及在第 7 行显示错误

[ $((year % 4)) -eq 0] 

回答by anubhava

You've made it too complicated. Use this code to figure leap year:

你把它弄得太复杂了。使用此代码计算闰年:

isleap() { 
   year=
   (( !(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

回答by Jens

You miss some blanks which are nesessary in bash:

你错过了一些在 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

回答by Prem Aswar

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