本文我们讨论一下
程序控制语句之一:选择
Shell的分支语句有以下这几个:
if else;
in case;
一、if else 选择:
最简单的if
语法:
if condition
then
statement
fi
如果喜欢把if和then写成一行,要加;
if condition;then
statement
fi
示例:
[root@localhost shell_protest]# sh if.sh
hello
---------------Source----------------
[root@localhost shell_protest]# cat if.sh
#!/bin/bash
if true
then
echo hello
fi
if-else:
if condition
then
statement1
else
statement2
fi
示例:判断a、b是否相等
[root@localhost shell_protest]# sh ifelse.sh
11
22
a!=b
---------------Source----------------
[root@localhost shell_protest]# cat ifelse.sh
#!/bin/bash
read a
read b
if (( $a == $b ))
then
echo "a=b"
else
echo "a!=b"
fi
多重if elseif在shell里面又怎么写?
语法:
if condition1
then
statement1
elif condition2
then
statement2
elif condition3
then
statement3
……
else
statementn
fi
示例:判断星期几
[root@localhost shell_protest]# sh whichday.sh
Input integer number: 3
Wednesday
---------------Source----------------
[root@localhost shell_protest]# cat whichday.sh
#!/bin/bash
printf "Input integer number: "
read num
if ((num==1)); then
echo "Monday"
elif ((num==2)); then
echo "Tuesday"
elif ((num==3)); then
echo "Wednesday"
elif ((num==4)); then
echo "Thursday"
elif ((num==5)); then
echo "Friday"
elif ((num==6)); then
echo "Saturday"
elif ((num==7)); then
echo "Sunday"
else
echo "error"
fi
二、Case in
语法:
case 变量 in
情况一)
statement1
;;
情况二)
statement2
;;
*)
default statement
esac
示例:判断周几?
[root@localhost shell_protest]# sh case.sh
Input integer number: 2
Tuesday
---------------Source----------------
[root@localhost shell_protest]# cat case.sh
#!/bin/bash
printf "Input integer number: "
read num
case $num in
1)
echo "Monday"
;;
2)
echo "Tuesday"
;;
3)
echo "Wednesday"
;;
4)
echo "Thursday"
;;
5)
echo "Friday"
;;
6)
echo "Saturday"
;;
7)
echo "Sunday"
;;
*)
echo "error"
esac
本文深入探讨了Shell编程中的选择控制语句,包括if else的基本用法,如简单的if条件判断及多重if elseif的实现。此外,还详细介绍了case in结构,通过实例展示了如何根据条件判断当前是星期几。

1万+

被折叠的 条评论
为什么被折叠?



