Unix / Linux Shell - if...fi 语句


if ...fi语句是基本的控制语句,它允许 Shell 做出决策并有条件地执行语句。

句法

if [ expression ] 
then 
   Statement(s) to be executed if expression is true 
fi

Shell表达式按上述语法求值。如果结果值为true,则执行给定的语句。如果表达式,则不会执行任何语句。大多数时候,比较运算符用于做出决策。

建议小心大括号和表达式之间的空格。没有空格会产生语法错误。

如果表达式是一个 shell 命令,那么执行后如果返回0,则假定为 true 。如果是布尔表达式,则返回 true 则为 true。

例子

#!/bin/sh

a=10
b=20

if [ $a == $b ]
then
   echo "a is equal to b"
fi

if [ $a != $b ]
then
   echo "a is not equal to b"
fi

上面的脚本将生成以下结果 -

a is not equal to b
unix-决策.htm