case判斷
變量名 in
value1)
command
;;
value2)
command
;;
*)
commond
;;
esac
- 在case程序中,能夠在條件中使用|,表示或的意思, 好比
2|3)
command
;;
shell腳本案例:
- 腳本目的是 輸入一個數字,而後用腳本去判斷這個數字的範圍
[root@hf-01 shell]# read -p "dfd" z
dfdgb
[root@hf-01 shell]# read -p "dfd: " z
dfd: fgdg
[root@hf-01 shell]#
#!/bin/bash
#判斷是否輸入有數值,空直接結束整個文本
read -p "Please input a number: " n
#read 讓用戶輸出一些字符串;賦值給最後一個變量;這裏的賦值是「n」
if [ -z "$n" ] //變量n 爲空
then
echo "Please input a number."
exit 1 // 知識點 1
fi
#n1將輸入的數值清空數字,檢查變量是否爲空,若是不爲空,就證實輸入有其餘的字符,告知用戶,請輸入一個數字
n1=`echo $n|sed 's/[0-9]//g'` //肯定,n變量是否爲數字
if [ -n "$n1" ]
then
echo "Please input a number."
exit 1
fi
if [ $n -lt 60 ] && [ $n -ge 0 ]
then
tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
tag=2
elif [ $n -ge 80 ] && [ $n -lt 90 ]
then
tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
tag=4
else
tag=0
fi
case $tag in
1)
echo "not ok"
;;
2)
echo "ok"
;;
3)
echo "ook"
;;
4)
echo "oook"
;;
*)
echo "The input value exceeds the calculation range.The number range is 0-100."
;;
esac
知識點 1
- shell 中 exit0 exit1 的區別:
- exit(0):正常運行程序並退出程序;
- exit(1):非正常運行致使退出程序;
- exit 0 能夠告知你的程序的使用者:你的程序是正常結束的。若是 exit 非 0 值,那麼你的程序的使用者一般會認爲你的程序產生了一個錯誤。
- 在 shell 中調用完你的程序以後,用 echo $? 命令就能夠看到你的程序的 exit 值。在 shell 腳本中,一般會根據上一個命令的 $? 值來進行一些流程控制。