确认是否要改变COUNTER的值。如果输入Y或者y,则继续输入要累加的数字,输入非法数字或者未输入则直接退出程序,输入正常数字则计算累加到COUNTER;输入Y或者y以外的值则退出程序。
#!/bin/bash
COUNTER=100
echo -n "Do you want to change your $COUNTER?[Y or N]:"
read ANS
if [ "$ANS" = "Y" ] || [ "$ANS" = "y" ] ; then
echo "Please enter your number:"
read VALUE
expr $VALUE + 10 >/dev/null 2>&1
if [ $? != 0 ] || [ $VALUE = "" ] ;then
echo "You enter illegal digit!"
exit 1
fi
COUNTER=`expr $COUNTER + $VALUE`
echo "The new COUNTER is $COUNTER !"
else
echo "I don't wish to change COUNTERS."
exit 1
fi
[root@localhost home]# ./ifcounter.sh
Do you want to change your 100?[Y or N]:N
I don't wish to change COUNTERS.
[root@localhost home]# ./ifcounter.sh
Do you want to change your 100?[Y or N]:y
Please enter your number:
ssd
You enter illegal digit!
[root@localhost home]# ./ifcounter.sh
Do you want to change your 100?[Y or N]:Y
Please enter your number:
3
The new COUNTER is 103 !
注意点:if [ "$ANS" = "Y" ] || [ "$ANS" = "y" ],中括号前后要有空格,=号前后也要有空格
特别说明:本文是学习David Tansley 《 Linux and UNIX Shell Programming》实体书之后整理的,因本站必需填写url,文章类型写成了原创。在此分享,以供大家一起学习。如有不良影响,请联系本人删除。