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 脚本中,一般会根据上一个命令的 $? 值来进行一些流程控制。