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;
相关文章推荐
- bash脚本之for语句if语句以及各种测试语句(2)
- linux shell if else 多个选择条件的判断语句 语法
- shell脚本之if语句
- linux Shell脚本之测试语句
- 书写优雅的shell脚本(一)- if语句
- Linux的Shell脚本中IF流程控制语句的基本语法
- linux shell编程之——if语句
- Linux Shell脚本应用——使用if判断结构
- if嵌套语句 shell脚本实例 测试是否闰年
- Linux shell awk 流程控制语句(if,for,while,do)详细介绍
- linux shell编程if语句内判断参数(1)
- shell的一些常用的语句(if语句,变量,for、while、until语句、函数调用、脚本调用)
- Linux shell脚本之 if条件判断
- Shell 脚本基础 - 使用 if 语句进行条件检测
- Shell脚本应用(if语句的结构)
- linux shell 流程控制(条件if,循环【for,while】,选择【case】语句实例
- linux shell 流程控制(条件if,循环【for,while】,选择【case】语句实例
- shell脚本中if流程控制语句的应用
- shell脚本编程之for语句、if语句使用介绍
- Linux shell脚本——if运算例子