当前位置: > shell编程 >

shell脚本if else语句简明教程

时间:2014-07-28 13:05来源:linux.it.net.cn 作者:it

注意,在linux shell编程中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

在shell脚本中,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!

(责任编辑:IT)
------分隔线----------------------------
栏目列表
推荐内容