Shell 脚本基础 - 使用 if 语句进行条件检测
2014-12-21 10:31
1316 查看
Bourne Shell 的 if 语句和大部分编程语言一样 - 检测条件是否真实,如果条件为真,shell 会执行这个 if 语句指定的代码块,如果条件为假,shell 就会跳过 if 代码块,继续执行之后的代码。
基本 if 语句的嵌套语法:
作者:Pradeep Kumar 译者:ThomazL 校对:wxy
if 语句的语法:
if [ 判断条件 ] then command1 command2 …….. last_command fi
Example:
#!/bin/bash number=150 if [ $number -eq 150 ] then echo "Number is 150" fi
if-else 语句:
除了标准的 if 语句之外,我们还可以加入 else 代码块来扩展 if 语句。这么做的主要目的是:如果 if 条件为真,执行 if 语句里的代码块,如果 if 条件为假,执行 else 语句里的代码块。语法:
if [ 判断条件 ] then command1 command2 …….. last_command else command1 command2 …….. last_command fi
Example:
#!/bin/bash number=150 if [ $number -gt 250 ] then echo "Number is greater" else echo "Number is smaller" fi
If..elif..else..fi 语句 (简写的 else if)
Bourne Shell 的 if 语句语法中,else 语句里的代码块会在 if 条件为假时执行。我们还可以将 if 语句嵌套到一起,来实现多重条件的检测。我们可以使用 elif 语句(else if 的缩写)来构建多重条件的检测。语法 :
if [ 判断条件1 ] then command1 command2 …….. last_command elif [ 判断条件2 ] then command1 command2 …….. last_command else command1 command2 …….. last_command fi
Example :
#!/bin/bash number=150 if [ $number -gt 300 ] then echo "Number is greater" elif [ $number -lt 300 ] then echo "Number is Smaller" else echo "Number is equal to actual value" fi
多重 if 语句 :
If 和 else 语句可以在一个 bash 脚本里相互嵌套。关键词 “fi” 表示里层 if 语句的结束,所有 if 语句必须使用 关键词 “fi” 来结束。基本 if 语句的嵌套语法:
if [ 判断条件1 ] then command1 command2 …….. last_command else if [ 判断条件2 ] then command1 command2 …….. last_command else command1 command2 …….. last_command fi fi
Example:
#!/bin/bash number=150 if [ $number -eq 150 ] then echo "Number is 150" else if [ $number -gt 150 ] then echo "Number is greater" else echo "'Number is smaller" fi fi
作者:Pradeep Kumar 译者:ThomazL 校对:wxy
相关文章推荐
- Shell 脚本基础 - 使用 if 语句进行条件检测
- shell脚本编程:条件判断if语句使用小结
- shell脚本不使用if语句进行选择的脚本
- shell基础之二:条件判断语句if、case及read命令,
- shell脚本编程之for语句、if语句使用介绍
- Shell脚本基础5-if-then语句
- 使用if语句编写Shell脚本
- shell脚本编程之for语句、if语句使用介绍
- shell脚本的使用---if条件判断
- Shell脚本入门(六) - 条件控制语句: if
- shell脚本之-if流程控制语句和for循环语句的使用
- shell脚本基础应用(二)if单分支,双分支,多分支语句
- Java基础知识-if条件语句的使用介绍
- shell脚本编程之for语句、if语句使用介绍
- shell脚本实例 使用exit语句和if
- Shell脚本基础6-if语句练习-文件测试操作
- Shell脚本基础 、 使用变量 、 条件测试及选择 、 列表式循环
- Shell使用if条件语句
- 续写vim,shell脚本基础编辑,read命令,if与case判断语句,文件查找方式,压缩与解压,
- 使用for、if语句添加用户的一个shell脚本