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

Shell脚本if else语句小结


和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!

Shell脚本case语句简明教程
Shellcase语句为多选择语句。可以用case语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。case语句格式如下:case值in模式1)command1command2...com

Shell脚本for循环语句简明教程
与其他编程语言类似,Shell支持for循环。for循环一般格式为:for变量名in列表docommand1command2...commandNdone当变量值在列表里,for循环即执行一次所有命令,

Shell脚本while、until循环语句简明教程
一、while循环while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:while命令docommand1command2...commandNdone命