当前位置: 移动技术网 > 网络运营>服务器>Linux > Shell脚本if else语句小结

Shell脚本if else语句小结

2017年12月12日  | 移动技术网网络运营  | 我要评论

和java、php等语言不一样,sh的流程控制不可为空,如:

复制代码 代码如下:

<?php
if (isset($_get["q"])) {
    search(q);
}
else {
    //do nothing
}
?>

在sh/bash里可不能这么写,如果else分支没有语句执行,就不要写这个else,就像这样:

复制代码 代码如下:

if condition
then
    command1
    command2
    ...
    commandn
fi

当然,也可以写成一行(适用于终端命令提示符),像这样:

复制代码 代码如下:

if test $[2*3] -eq $[1+5]; then echo 'the two numbers are equal!'; fi;

末尾的fi就是if倒过来拼写,后面还会遇到类似的。

if else格式

复制代码 代码如下:

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

if else-if else格式

复制代码 代码如下:

if condition1
then
    command1
elif condition2
    command2
else
    commandn
fi

if else语句经常与test命令结合使用,如下所示:

复制代码 代码如下:

num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'the two numbers are equal!'
else
    echo 'the two numbers are not equal!'
fi

输出:
the two numbers are equal!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网