Linux 下shell中if分支结构

来源:互联网 发布:对虚拟网络的看法 编辑:程序博客网 时间:2024/05/21 19:42
if 结构
if 语句
if 语句的结构如下:
单分支结构
if condition
then
statement1
statement2
..........

fi

双分支结构
if condition
then
statement1
statement2
..........
else
statement3
..........
fi

多分支结构
if condition1
then
statement1
statement2
..........
elif condition2
then
statement3
statement4
..........
elif condition3
then
statement5
statement6
..........
fi

多分支结构

if condition1
then
statement1
statement2
..........
elif condition2
then
statement3
statement4
..........
elif condition3
then
statement5
statement6
..........
else
statement7
..........
fi

if 语句使用举例
下面举几个使用 if 语句的例子:
例1:
#!/bin/bash
# filename: areyouok.sh
echo "Are you OK ?"
read answer
# 在 if 的条件判断部分使用扩展的 test 语句 [[...]]
# [[]] 中可以使用正则表达式进行条件匹配
if [[ $answer == [Yy]* || $answer == [Mm]aybe ]]
then
echo "Glad to hear it."
fi

例2:
#!/bin/bash
# filename: myssh.sh
# 在条件测试中判断位置参数的个数 $#
if [ "$#" -eq "2" ]; then
 ssh $1@$2
else
 echo "Usage: $0 <username> <FQDN or IPAdress>"
fi

原创粉丝点击