选择语句if else和 case in
Shell 也支持选择结构,并且有两种形式,分别是 if else 语句和 case in 语句
if else 语句
有三种语法结构:
语法一:
if [ 条件表达式 ];then
命令序列
fi
语义:当条件表达式的测试值为真时,执行命令序列,否则执行条件语句后面的命令
示例:
[root@system1 ~]# vim test02.sh
#!/bin/bash
##判断当前目录下是否存在文件##
echo "Enter a file name:"
read file
if [ -f $file ];then
echo "The file $file exits!"
fi
运行结果:
[root@system1 ~]# chmod a+x ./test02.sh
[root@system1 ~]# ./test02.sh
Enter a file name:
a
[root@system1 ~]# ./test02.sh
Enter a file name:
test.sh
The file test.sh exits!
语法二
if [ 条件表达式 ]
then
命令序列1
else
命令序列2
fi
示例:
[root@system1 ~]# vim test03.sh
#!/bin/bash
##判断指定用户是否和当前用户一致,并输出相关信息##
echo -n "Enter your login name:"
read name
if [ "$name" = "$USER" ];
then
echo "Hello,$name"
else
echo "You are not $USER"
fi
运行:
[root@system1 ~]# ./test03.sh
Enter your login name:root
Hello,root
[root@system1 ~]# ./test03.sh
Enter your login name:haha
You are not root
语义:当条件表达式的测试值为真时,执行命令序列1,否则执行命令序列2
语法三:
if test 条件表达式1
then
命令序列1
elif [ 条件表达式2 ]
then
命令序列2
else
命令序列3
fi
语义:当条件表达式1为真时执行命令序列1,否则在条件表达式2为真时执行命令序列2,否则执行命令序列3
示例:
#!/bin/bash
##比较两个数的大小##
echo "Enter the first integer:"
read first
echo "Enter the second integer:"
read second
if [ "$first" -gt "$second" ]
then
echo "$first is greater than $second"
elif [ "$first" -lt "$second" ]
then
echo "$first is less than $second"
else
echo "$first is equal to $second"
fi
运行:
[root@system1 ~]# chmod a+x ./test04.sh
[root@system1 ~]# ./test04.sh
Enter the first integer:
2
Enter the second integer:
3
2 is less than 3
[root@system1 ~]# ./test04.sh
Enter the first integer:
1
Enter the second integer:
1
1 is equal to 1
case in 语句
当某个变量或表达式存在多种取值,不同的取值决定不同的行为动作,如果取值较多,则使用if语句会让逻辑变得复杂,在这种情况下,可以使用分支语句
语法:
case 变量 in
值1)
命令序列1
;;
值2)
命令序列2
;;
......
值n)
命令序列n
;;
esac
语义:当变量的值为值1时执行命令序列1,为值2时执行命令序列2,以此类推,注意,在每个命令序列后,使用";;"作为结束标记
特殊字符:
* 匹配所有字符串
? 匹配任意单个字符
[...] 定义某个范围内的字符集合
| 分割不同的值,表示"或者"
示例:
#!/bin/bash
##判断当前系统时间##
hour=`date +%H`
case $hour in
0[1-9]|[01])
echo "Good morning!"
;;
1[2-7])
echo "Good afternoon!"
;;
*)
echo "Good evening!"
;;
esac
运行:
[root@system1 ~]# ./test05.sh
Good afternoon!