多分支案例
案例一:
两个整数比较大小。
条件:输入两个数字(必须是数字)
脚本程序:
#! /bin/bash
read -p "请输入两个数字" num1 num2
if [ $num1 -gt $num2 ]
then
echo "$num1>$num2"
elif [ $num1 -lt $num2 ]
then
echo "$num1<$num2"
else
echo "$num1=$num2"
fi
结果:
[root@localhost ~]# vim shell.sh
[root@localhost ~]# ./shell.sh
请输入两个数字2 3
2<3
[root@localhost ~]# ./shell.sh
请输入两个数字3 2
3>2
[root@localhost ~]# ./shell.sh
请输入两个数字3 3
3=3
案例二:
通过用户输入的成绩,判断用户级别。
#! /bin/bash
read -p "请输入成绩:" gread
if [ $gread -ge 95 ]
then
echo "$gread>=95,完美"
elif [ $gread -ge 85 ]
then
echo "95>$gread>=85,优秀"
elif [ $gread -ge 75 ]
then
echo "85>$gread>=75,良"
elif [ $gread -ge 60 ]
then
echo "75>$gread>=60,及格"
else
echo "不及格"
fi
结果:
[root@localhost ~]# ./shell1.sh
请输入成绩:60
75>60>=60,及格
[root@localhost ~]# ./shell1.sh
请输入成绩:85
95>85>=85,优秀
[root@localhost ~]# ./shell1.sh
请输入成绩:95
95>=95,完美
[root@localhost ~]# ./shell1.sh
请输入成绩:78
85>78>=75,良
优化以上程序:
#! /bin/bash
read -p "请输入成绩:" gread
if let gread++ 2>/dev/null
then
if [ $gread -ge 0 -a $gread -le 100 ]
#控制数字输入的范围,因为为百分制
then
if [ $gread -ge 95 ]
then
echo "$gread>=95,完美"
elif [ $gread -ge 85 ]
then
echo "95>$gread>=85,优秀"
elif [ $gread -ge 75 ]
then
echo "85>$gread>=75,良"
elif [ $gread -ge 60 ]
then
echo "75>$gread>=60,及格"
else
echo "不及格"
fi
else
echo "超出分数范围"
exit 3
fi
else
echo "输入的不是整数"
echo 5
fi
案例三:
根据用户输入,判断是数字,字母或者是其他字符。
#! /bin/bash
read -p "请输入字母,数字或字符:" var
if echo "$var" | egrep "^[a-zA-Z]*$" &>/dev/null
then
echo "is letter"
elif echo "$var" | egrep "^[0-9]*$" &>/dev/null
then
echo "is number"
else
echo "is other"
fi
结果:
[root@localhost ~]# vim shell2.sh
[root@localhost ~]# ./shell2.sh
请输入字母,数字或字符:qqq
is letter
[root@localhost ~]# ./shell2.sh
请输入字母,数字或字符:123
is number
[root@localhost ~]# ./shell2.sh
请输入字母,数字或字符:qww122
is other
案例四:
判断当前主机的CPU生产商,其信息在/proc/cpuinfo文件中vendor_id一行中。
条件: 如果其生产商为Genuineltel,显示为Intel
如果其生产商为AuthenticAMD,显示为AMD
否则,就显示无法识别
脚本代码:
#! /bin/bash
vendor=$(grep "vendor_id" /proc/cpuinfo | uniq | awk -F: '{print $NF}')
#取出要比较的值,赋值给变量
if [[ $vendor == [[:space:]]*GenuineIntel$ ]]
then
echo "Intel"
elif [[ $vendor == [[:space:]]*AuthenticAMD$ ]]
then
echo "AMD"
else
echo "other"
fi
结果:
[root@localhost ~]# vim shell3.sh
[root@localhost ~]# ./shell3.sh
other