本文参考LinuxTechi网站中这篇文章:How to check Conditions with if statement in shell Scripting(by Pradeep Kumar · Published October 26, 2014 · Updated August 3, 2017 )整理译出,并添加部分标注。
在Bourne Shell中,if语句检查条件是否为真。如果是这样,shell执行与if语句关联的代码块。如果该语句不正确,那么shell将跳出if语句块的结尾并继续。
if [condition_command]
then
command1
command2
...... ..
last_command
fi
Example:
#!/bin/bash
number=150
if [ $number -eq 150 ]
then
echo "Number is 150"
fi
除了正常的if语句外,我们还可以用else语句扩展if语句。基本思想是,如果语句正确,则执行if块。如果该语句为false,则执行else块 。
Syntax :
if [ condition_command ]
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
Syntax :
if [ condition_command ]
then
command1
command2
……..
last_command
elif [ condition_command2 ]
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
如果statement和else语句可以嵌套在bash脚本中。关键字’fi’显示内部if语句的结尾,所有if语句都应以关键字’fi’结尾。
Syntax :
if [ condition_command ]
then
command1
command2
……..
last_command
else
if [ condition_command2 ]
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
[本人标注]
总结:
整数比较
-eq
(equals) int1 -eq int2 两数相等为真
-ne
(not equals) int1 -ne int2 两数不等为真
-gt
(greater) int1 -gt int2 int1大于int2为真
-ge
int1 -ge int2 int1大于等于int2为真
-lt
int1 -lt int2 int1小于int2为真
-le
int1 -le int2 int1小于等于int2为真
1. -eq 等于,如:if [ "a" -eq "b" ]
2. -ne 不等于,如:if [ "a" -ne "b" ]
3. -gt 大于,如:if [ "a" -gt "b" ]
4. -ge 大于等于,如:if [ "a" -ge "b" ]
5. -lt 小于,如:if [ "a" -lt "b" ]
6. -le 小于等于,如:if [ "a" -le "b" ]
7. < 小于(需要双括号),如:(("a" < "b"))
8. <= 小于等于(需要双括号),如:(("a" <= "b"))
9. > 大于(需要双括号),如:(("a" > "b"))
10. >= 大于等于(需要双括号),如:(("a" >= "b"))
参考链接
1、If / Else Statements (Shell Scripting)
2、How to check Conditions with if statement in shell Scripting
3、第十二章、學習 Shell Scripts[推荐]