Shell腳本之鳥哥私房菜第13章sh11

 

最近在看《鳥哥的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

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章