【shell一天一练】检查日期

115 阅读1分钟

今日小练题目📢

写一个脚本判断给定的一串数字是否是合法的日期

优秀作业🤌🏻

#!/bin/bash
# author: xYLiuuuuuu
# version:v1
# date: 2024-12-11

if [ $# -ne 1 ] || [ ${#1} -ne 8 ]
then
        echo "Usage: bash $0 yyyymmdd"
        exit 1
fi

mydate=$1
year=${mydate:0:4}
month=${mydate:4:2}
day=${mydate:6:2}

if ! [[ $year =~ ^[0-9]+$ && $month =~ ^[0-9]+$ && $day =~ ^[0-9]+$ ]]; then
        echo "The date is Error.Not all components are numbers."
        exit 1
fi

if [ $month -lt 1 ] || [ $month -gt 12 ]; then
        echo "The date is Error.Month is out of range."
        exit 1
fi

if cal $month $year 2>/dev/null | grep -q "$day"; then
        echo "The date is OK. The date is $year$month$day 日"
else
        echo "The date is Error. Day is invalid for the given month and year."
fi

敲黑板📝

  • $#表示参数个数,${#1}表示第一个参数的长度
  • ${a:n1:n2}表示变量a从第n1(从0开始算)个字符开始截取,一共截取n2个
  • cal为linux的日志,cal 月年; cal年; cal
  • =~是判断正则的等号
  • ^[0-9]+$数字