1、单if语法vim
一、语法格式:bash
if [ condition ] #condition值为 then commands fi
二、举例:spa
[root@localhost test20210725]# vim document.sh #!/usr/bin/bash #假如没有/tmp/abc这个文件夹,就建立一个 if [ ! -d /tmp/abc ] then mkdir -pv /tmp/abc
echo "文件建立成功"
fi
查看运行结果:code
[root@localhost test20210725]# sh document.sh mkdir: created directory ‘/tmp/abc’ 文件建立成
2、if...else语法blog
一、语法格式:数学
if [ condition ] #condition值为 then commands1 else commands2 fi
二、举例:it
[root@localhost test20210725]# vim document2.sh #!/usr/bin/bash #假如没有/tmp/abc这个文件夹,就建立一个,不然打印信息 if [ ! -d /tmp/abc ] then mkdir -pv /tmp/abc echo "文件建立成"
else echo "文件已经存在,再也不建立" fi
查看运行结果:io
[root@localhost test20210725]# sh document2.sh mkdir: created directory ‘/tmp/abc’ 文件建立成 [root@localhost test20210725]# sh document2.sh 文件已经存在,再也不建立
3、if...elif...else语法class
一、语法格式:test
if [ condition1 ] #condition值为 then commands1
elif [ condition2 ]
then
commands2
......
else commandsx fi
二、举例说明:
[root@localhost test20210725]# vim number3.sh #!/usr/bin/bash #脚本传递两个数字参数并比较 if [ $1 -eq $2 ] then echo "$1 = $2" elif [ $1 -gt $2 ] then echo "$1 > $2"
else echo "$1 < $2"
fi
查看运行结果:
[root@localhost test20210725]# sh number3.sh 1 1
1 = 1 [root@localhost test20210725]# sh number3.sh 2 1
2 > 1 [root@localhost test20210725]# sh number3.sh 1 3
1 < 3
4、if高级语法
一、使用(())植入数学表达式作运算,举例:
[root@localhost test20210725]# vim if_avg.sh #!/usr/bin/bashif (( 100%3+1>1 )) then echo "yes"
else echo "no" fi
查看运行结果:
[root@localhost test20210725]# sh if_avg.sh
yes
二、使用[[]]能够在条件中使用通配符,举例:
[root@localhost test20210725]# vim if_avg2.sh #!/usr/bin/bash for i in r1 rr2 cc rr3 do
if [[ $i == r* ]];then echo $i fi done
查看运行结果:
[root@localhost test20210725]# sh if_avg2.sh
r1
rr2
rr3