最近在看《鸟哥的Linux私房菜基础学习篇(第三版)》中的第13章.
作者在讲解-多重、复杂条件判断式的时候,举了一个例子。输入某人的退伍日期,然后计算他还有几天退伍?
这个例子也就是书中的脚本sh11.sh
这里我们把这个脚本稍微完善一下,
增加的功能如下:
1)增加对日期有效性的简单检查,比如月份不可能大于12,日期不能大于31,输入20150231这样的日期肯定是不行的,2月份是不可能有31天的
脚本中不足之处:
1)即使是日期的校验,也并没有对于普通年份和闰年的的2月份这样的特殊日期进行检查
2)输入的日期只是提示说需要大于20140314,但是并没有对输入日期的有效性进一步的进行检查,比如,如果输入昨天的日期,应该是不允许的
3)程序的本意是希望能够打印出月份的英文名称,但是如何将case使用的变量和数字进行比较目前还不了解
不多啰嗦了,直接上源码,文件名同样命令为是sh11.sh
#!/bin/bash
#Program:
# You input your demobilization date, I calculate how many days before you demobilize
#History
#2014/02/11 haiqinma First release
export PATH
echo "This program will try to calculate:"
echo "How many days before your demobilization date..."
read -p "Please input your demobilization deate(YYYYMMDD ex>20140314):" date2
date_d=$(echo $date2|grep '[0-9]\{8\}')
echo "The date your input is $date_d"
date_length=${#date_d}
echo "The length of input is $date_length"
if [ "$date_length" != "8" ]; then
echo "the length of your input is not right"
exit 1
fi
date_year=${date_d:0:4}
echo "The year of input is $date_year"
date_month=${date_d:4:2}
echo "The month of input is $date_month"
if [ $date_month -lt 00 ] || [ $date_month -gt 12 ]; then
echo "You input the wrong date formate--month"
exit 1
fi
date_day=${date_d:6:2}
echo "The day of input is $date_day"
if [ $date_day -gt 31 ]; then
echo "You input the wrong date fromate--day"
exit 1
fi
if [ $date_day -eq 31 ]; then
case $date_mont in
"01")
echo "Month-Jan"
;;
"03")
echo "Month-Mar"
;;
"05")
;;
"07")
;;
"08")
;;
"10")
;;
"12")
;;
*)
echo "the day and month are mismach"
exit 1
;;
esac
fi
declare -i date_dem=`date --date="$date2" +%s`
declare -i date_now=`date +%s`
declare -i date_total_s=$(($date_dem-$date_now))
declare -i date_d=$(($date_total_s/60/60/24))
if [ "$date_total_s" -lt "0" ];then
echo "You had been demobilization befor:"$((-1*$date_d))"ago"
else
declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60))
echo "You will demobilize after $date_d days and $date_h hours"
fi