zl程序教程

您现在的位置是:首页 >  其他

当前栏目

20.8/20.9 case判断

2023-04-18 16:55:32 时间

case判断

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