• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

判断输入的日期是否正确的shell脚本

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

今儿个讲得是判断输入的日期是否正确,有利用到我们之前03这个例子中的函数
下面是代码

#!/bin/sh
# valid-date -- Validates a date, taking into account leap year rules.

exceedsDaysInMonth()
{

 case $(echo $1|tr '[:upper:]' '[:lower:]') in
  jan* ) days=31  ;; feb* ) days=28  ;;
  mar* ) days=31  ;; apr* ) days=30  ;;
  may* ) days=31  ;; jun* ) days=30  ;;
  jul* ) days=31  ;; aug* ) days=31  ;;
  sep* ) days=30  ;; oct* ) days=31  ;;
  nov* ) days=30  ;; dec* ) days=31  ;;
  * ) echo "$0: Unknown month name $1" >&2; exit 1
  esac

  if [ $2 -lt 1 -o $2 -gt $days ] ; then
   return 1
  else
   return 0  # the day number is valid
  fi
}

isLeapYear()
{

 year=$1
 if [ "$((year % 4))" -ne 0 ] ; then
  return 1 # nope, not a leap year
 elif [ "$((year % 400))" -eq 0 ] ; then
  return 0 # yes, it's a leap year
 elif [ "$((year % 100))" -eq 0 ] ; then
  return 1
 else
  return 0
 fi
}
## Begin main script

if [ $# -ne 3 ] ; then
 echo "Usage: $0 month day year" >&2
 echo "Typical input formats are 8 3 2002" >&2
 exit 1
fi

# Normalize date and split back out returned values


if [ $? -eq 1 ] ; then
 exit 1    # error condition already reported by normdate
fi

monthnoToName()
{
 # Sets the variable 'month' to the appropriate value
 case $1 in
  01|1 ) monthd="Jan"  ;; 02|2 ) monthd="Feb"  ;;
  03|3 ) monthd="Mar"  ;; 04|4 ) monthd="Apr"  ;;
  05|5 ) monthd="May"  ;; 06|6 ) monthd="Jun"  ;;
  07|7 ) monthd="Jul"  ;; 08|8 ) monthd="Aug"  ;;
  09|9 ) monthd="Sep"  ;;   10) monthd="Oct"  ;;
    11) monthd="Nov"  ;;   12) monthd="Dec"  ;;
  * ) echo "$0: Unknown numeric month value $1" >&2; exit 1
  esac
  return 0
}

monthnoToName $1

month="$monthd"
 day="$2"
 year="$3"
 
if ! exceedsDaysInMonth $month "$2" ; then
 if [ "$month" = "Feb" -a "$2" -eq "29" ] ; then
  if ! isLeapYear $3 ; then
   echo "$0: $3 is not a leap year, so Feb doesn't have 29 days" >&2
   exit 1
  fi
 else
  echo "$0: bad day value: $month doesn't have $2 days" >&2
  exit 1
 fi
fi

echo "Valid date: $newdate"

exit 0

分析:
1)首先判断用户输入的参数个数是否正确,接着case $1 in 语句判断月份是否合理。
2)monthnoToName 函数之前出现在我们之前的第03个脚本案例中,用来转换输入的数字日期为字符串。
3) exceedsDaysInMonth 用来判断天数是否超过对应月的最大天数,紧跟着 if [ "$month" = "Feb" -a "$2" -eq "29" ] ; then if ! isLeapYear $3 ; then 用来判断闰年2月的特殊情况
4)总体的感觉是脚本还是很紧凑的,特别是在判断闰年与2月的关系的那段代码,有点意思。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
shell脚本echo输出不换行功能增强实例发布时间:2022-02-11
下一篇:
linux shell实现判断输入的数字是否为合理的浮点数发布时间:2022-02-11
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap