0
点赞
收藏
分享

微信扫一扫

Shell 快速入门(十二):选择结构怎么写

与其他语言一样 Shell 也有 IF-ELSE 以及 IF-ELSE-IF-ELSE 的选择结构。

IF ELSE 结构

Shell 语言中的 IF - ELSE 选择结构语法格式如下:

if condition
then
command1
command2
...
commandN
else
command
fi

例如:

a=10
b=10
if [ $a = $b ]
then
echo "a equals b" # 输出这里
fi

IF ELSE-IF ELSE 结构

Shell 语言中的 IF ELSE-IF ELSE 结构语法格式如下:

if condition1
then
command1
elif condition2
then
command2
else
commandN
fi

例如:

a=9 
if [ $a = 10 ]
then
echo "a == 10"
elif [ $a -lt 10 ]
then
echo "a < 10" # 输出这里
else
echo "a > 10"
fi

特别需要注意的是 if 后面的表达式,其左右两边都要留有一个空格,这是 Shell 的语法。如果没有空格,那么 Shell 执行的时候会报错。例如下面的 Shell 就会报错:

a=10 
if [$a = 10 ]
then
echo "a is $a"
fi

执行之后,输出错误:​​-bash: [9: command not found​​​。出错原因就是因为在 if 后面的表达式​​$a​​前面少了一个空格。

Shell 快速入门(十二):选择结构怎么写_javascript



举报

相关推荐

0 条评论