確認是否要改變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,文章類型寫成了原創。在此分享,以供大家一起學習。如有不良影響,請聯繫本人刪除。