linux shell 条件判断if else, if elif else....
来源:互联网 发布:香港量健集团知乎 编辑:程序博客网 时间:2024/05/16 19:51
在linux的shell中
if 语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell 有三种 if ... else 语句:
if ... fi 语句; if ... else ... fi 语句; if ... elif ... else ... fi 语句。
1) if ... else 语句
if ... else 语句的语法:
if [ expression ]then Statement(s) to be executed if expression is truefi注意:如果 expression 返回 true,then 后边的语句将会被执行;如果返回 false,不会执行任何语句。
最后必须以 fi 来结尾闭合 if,fi 就是 if 倒过来拼写,后面也会遇见。
注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。
例如:
#!/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 Statement(s) to be executed if expression is trueelse Statement(s) to be executed if expression is not truefi如果 expression 返回 true,那么 then 后边的语句将会被执行;否则,执行 else 后边的语句。
举个例子:
#!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" else echo "a is not equal to b" fi
执行结果:
a is not equal to b
3) if ... elif ... fi 语句
if ... elif ... fi 语句可以对多个条件进行判断,语法为:if [ expression 1 ]then Statement(s) to be executed if expression 1 is trueelif [ expression 2 ]then Statement(s) to be executed if expression 2 is trueelif [ expression 3 ]then Statement(s) to be executed if expression 3 is trueelse Statement(s) to be executed if no expression is truefi哪一个 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 test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; 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!test 命令用于检查某个条件是否成立,与方括号([ ])类似。
阅读全文
0 0
- linux shell 条件判断if else, if elif else....
- python基础--条件判断:if..elif..else
- shell-007: if elif else
- shell语法if else elif
- Shell编程中if-elif-else条件分支语句测试
- python入门(三):条件判断 if elif else
- shell 中的条件判断(if else)
- Linux--Shell脚本(二)条件判断之if else
- 条件编译 #if, #elif, #else, #endif
- if-elif-else使用
- if-elif-else
- shell Learning [if elif else 的用法]
- Shell if elif else Code Example
- shell中的if elif else用法
- shell中if-elif-else用法
- Linux shell “if else” 与 条件判定
- js04.if...else条件判断
- python条件判断 if else
- 《一斛珠·元夜月蚀》
- 树莓派使用上spi tft!(fbtft的使用)
- j2ee规范-jdbc-存储过程调用(oracle为例)
- JavaSwing_1.1: FlowLayout(流式布局)
- C++之消除头文件嵌套包含
- linux shell 条件判断if else, if elif else....
- struts2
- 【C语言】冒泡法排序的三种实现方法
- JavaSwing_1.2: GridLayout(网格布局)
- 使用spring实现邮件的发送(含测试,源码,注释)
- 初探BeEF
- JavaSwing_1.3: GridBagLayout(网格袋布局)
- 【LeetCode】62. Unique Paths
- C++乱编系列之情人节单身狗