在任何一门语言中,判断语句总是少不了,今天来学习一下Shell中的if语句。
基本语法
单分支情况
- 第一种语法
if <条件表达式>
then
语句
fi
- 第二种语法
if <条件表达式>;then
语句
fi
其中条件表达式部分可以是test、[]、[[]]和(())等条件表达式。以上两种格式,可根据自己实际情况选择一种即可。
双分支情况
if <条件表达式>
then
语句
else
语句
fi
多分支情况
if <条件表达式>
then
语句
elif <条件表达式>
then
语句
elif <条件表达式>
then
语句
else
语句
fi
在多分支的if中,每个elif中后均需要带有then
分支嵌套情况
if <条件表达式>
then
if <条件表达式>
then
语句
fi
fi
在以上的写法注意缩进,方便阅读
建议在一个if嵌套不要超过三层
if与条件表达式语法
在前面讲过各个条件测试表达式,如test、[]、[[]]和(())等条件表达式,如下所示:
- 1、test表达式
if test <表达式>
then
语句
fi
- 2、[]表达式
if [ <表达式> ]
then
语句
fi
- 3、[ [ ] ]表达式
if [[ <表达式> ]]
then
语句
fi
- 4、(( ))表达式
if (( <表达式> ))
then
语句
fi
- 5、命令表达式
if 命令
then
语句
fi
if示例
1、if示例:判断文件是否且为普通文件
[root@localhost ~]# [ -f /etc/passwd ] && echo true || echo false
true
[root@localhost ~]# test -f /etc/passwd && echo true || echo false
true
与以下写法等效
[root@localhost Test]# cat if.sh
#!/bin/bash
if [ -f \"$1\" ]
then
echo true
else
echo false
fi
if test -f \"$2\"
then
echo true
else
echo false
fi
[root@localhost Test]# bash if.sh /etc/passwd /etc/hostssss
true
false
2、if示例:比较输入数字的大小
[root@localhost Test]# cat compareNum.sh
#!/bin/bash
a=$1
b=$2
echo \"Inputed number is:\" ${a} ${b}
if [ $# -ne 2 ]
then
echo \"input number must be 2 number.\"
exit 2
fi
expr $a + 2 &> /dev/null # 检查是否为整数
resulta=$?
expr $b + 2 &> /dev/null # 检查是否为整数
resultb=$?
if [ $resulta -eq 0 -a $resultb -eq 0 ] # 判断检查结果
then
if [ $a -gt $b ]
then
echo \"$a > $b\"
elif [ $a -lt $b ]
then
echo \"$a < $b\"
elif [ $a -eq $b ]
then
echo \"$a = $b\"
else
echo \"error\"
fi
else
echo \"please check your input\"
fi
[root@localhost Test]# bash compareNum.sh 1 # 输入一个数字
Inputed number is: 1
input number must be 2 number.
[root@localhost Test]# bash compareNum.sh a b # 输入字母
Inputed number is: a b
please check your input
[root@localhost Test]# bash compareNum.sh 900 89 # 输入两个数字
Inputed number is: 900 89
900 > 89
[root@localhost Test]# bash compareNum.sh 89 900
Inputed number is: 89 900
89 < 900
[root@localhost Test]# bash compareNum.sh 900 900
Inputed number is: 900 900
900 = 900
继续阅读与本文标签相同的文章
上一篇 :
Web安全-BurpSuite插件实战
下一篇 :
人工智能创造的人像 你能分辨哪张是真的吗
-
汇编(一) 汇编语言CPU、存储器、指令等概念
2026-05-19栏目: 教程
-
Github开源项目:Tamboot Cloud Admin一个基于spring cloud的微服务脚手架项目
2026-05-19栏目: 教程
-
Docker容器实战(三) - Docker的自我重新定位
2026-05-19栏目: 教程
-
阿里云注册域名使用教程
2026-05-19栏目: 教程
-
Docker容器实战(四) - 纷纷扰扰,终归尘土
2026-05-19栏目: 教程
