您的位置:首页 > 运维架构 > Shell

Linux shell脚本 (十一)if语句

2018-02-26 13:41 204 查看

if语句

​ if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if ... else 语句:if ... fi 语句;

if ... else ... fi 语句;

if ... elif ... else ... fi 语句。

1) if ... else 语句

if ... else 语句的语法:if [ expression ]
then
  ...
fi如果 expression 返回 true,then 后边的语句将会被执行;如果返回 false,不会执行任何语句。最后必须以 fi 来结尾闭合 if,fi 就是 if 倒过来拼写,后面也会遇见。注意:expression 和方括号[ ]之间必须有空格,if与[之间也要有空格,否则会有语法错误。举个例子:#!/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

2) if ... else ... fi 语句

if ... else ... fi 语句的语法:if [ expression ]
then
  ...
else
  ...
fi如果 expression 返回 true,那么 then 后边的语句将会被执行;否则,执行 else 后边的语句。举个例子:#!/bin/sh
a=10
b=20
if [ $a == $b ]
then  
echo "equal"
else  
echo "not equal"
fi执行结果:a is not equal to b

3) if ... elif ... fi 语句

if ... elif ... fi 语句可以对多个条件进行判断,语法为:if [ expression 1 ]
then
  ...
elif [ expression 2 ]
then
  ...
elif [ expression 3 ]
then
  ...
else
  ...
fi哪一个 expression 的值为 true,就执行哪个 expression 后面的语句;如果都为 false,那么不执行任何语句。举个例子:#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
  echo "a is equal to b"
elif [ $a -gt $b ]
then
  echo "a is greater than b"
elif [ $a -lt $b ]
then
  echo "a is less than b"
else
  echo "None of the condition met"
fi运行结果:a is less than b

if ... else 语句也可以写成一行,以命令的方式来运行,像这样:if [ 2 -eq 2 ]; then echo 'The two numbers are equal!'; fi;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: