我是个Linux入门“水手”,身上只有一本《鸟哥的linux私房菜基础篇》,把这本书当成我的进入
Linux领域的“葵花宝典”。鸟哥写的这本书讲的真不错,个人来说是新手开始学习Linux最最首选的一本
参考书,相信很多涉入了linux领域的新手或者高手,对此都深有感受吧。
今天看到了学习如何编写脚本的那一章节,里面有个脚本编写实例,题目是:
计算军人还有多少天可以退伍了。
脚本可完成的内容:
1.让使用者(军人)输入他退伍的日期。
2.再由现在的日期比对退伍的日期。
3.由两个日期的比较来显示(还需多久)才能退伍的字样。
---------------------以下是鸟哥编写的这个脚本内容----------------------------
#!/bin/bash
2 #program:
3 # you input your demobilization date,i calculate how many days
4 # before you demobilize.
5 #history:
6 #20120216 bobower first release
7 PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
8 export PATH
9
10
11 read -p "please input your demobilization.format like this's:>( 20121212 ):" date2
12
13
14 date_d=$(echo $date2 |grep '[0-9]\{8\}')
15
16
17
18 if [ "$date_d" == "" ]; then
19
20 echo "you input the wrong date format...." && exit 1
21
24 fi
25
26 declare -i date_dem=`date --date="$date2" +%s`
27 declare -i date_now=`date +%s`
28 declare -i date_total_s=$(($date_dem-$date_now))
29 declare -i date_d=$(($date_total_s/60/60/24))
30
31 if [ "$date_d" -lt "0" ]; then
32 echo "you had been demobilization before: $(($date_d*-1))"
33
34 else
35
36 declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60))
37
38 echo "you will demobilize after $date_d days and $date_h hours."
39 fi
试着运行一下,发现确实可以达到题目的要求。里面规定用户输入的日期格式只能为”20000101“这种的,
还做了一个条件判断,判断一下当输入的日期长度没有达到8个字符时,则提示”输入的日期格式错误“的
字样。。。。但鸟哥没有判断如果输入的日期长度超过8个字符时,该怎么办。所以 个人觉得这个脚本有点
这个缺陷。。呵呵,以下这个脚本是我通过鸟哥教我的方法弥补的这个缺陷。
1 #!/bin/bash
2 #program:
3 # you input your demobilization date,i calculate how many days
4 # before you demobilize.
5 #history:
6 #20120216 bobower first release
7 PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
8 export PATH
9
10
11 read -p "please input your demobilization.format like this's:>( 20121212 ):" date2
12
13
14 date_d=$(echo $date2 |grep '[0-9]\{8\}')
15
16 wc_m=$((`echo $date_d |wc -m`-1))
17
18 if [ "$date_d" == "" ]; then
19
20 echo "you input the wrong date format...." && exit 1
21 elif [ "$wc_m" -gt 8 ]; then
22 echo "you input date format very long...."
23 exit 2
24 fi
25
26 declare -i date_dem=`date --date="$date2" +%s`
27 declare -i date_now=`date +%s`
28 declare -i date_total_s=$(($date_dem-$date_now))
29 declare -i date_d=$(($date_total_s/60/60/24))
30
31 if [ "$date_d" -lt "0" ]; then
32 echo "you had been demobilization before: $(($date_d*-1))"
33
34 else
35
36 declare -i date_h=$(($(($date_total_s-$date_d*60*60*24))/60/60))
37
38 echo "you will demobilize after $date_d days and $date_h hours."
39 fi
只是在前面多增加了一个变量”$wc_m“和判断这个"$wc_m"的字符个数是否大于8.
其它的内容都是原封不动的啦。现在试着运行下这个脚本,不论使用都输入的字符个数大于8还是小于8,都
可以很好的做出判断了。。。。。