shell脚本中的逻辑判断
格式1:if 条件 ; then 语句; fi
格式2:if 条件; then 语句; else 语句; fi
格式3:if …; then … ;elif …; then …; else …; fi
逻辑判断表达式:if [ $a -gt $b ]; if [ $a -lt 5 ]; if [ $b -eq 10 ]等 -gt (>); -lt(=); -le(<=);-eq(==); -ne(!=) 注意到处都是空格
可以使用 && || 结合多个条件
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; then
shell脚本中的逻辑判断,shell注意点
for语句循环
[root@xuexi-001 ~]# for i in `seq 1 5`; do echo $i;done
1
2
3
4
5
[root@xuexi-001 ~]# for i in `seq 1 5`
> do
> echo $i
> done
1
2
3
4
5
if语句第一种格式
格式1:if 条件 ; then 语句; fi
[root@xuexi-001 ~]# a=5
[root@xuexi-001 ~]# if [ $a -gt 3 ]
> then
> echo ok
> fi
ok
脚本形式
[root@xuexi-001 shell]# vi if1.sh
#!/bin/bash
a=5
if [ $a -gt 3 ]
then
echo ok
fi
[root@xuexi-001 shell]# sh if1.sh
ok
if语句第二种格式
格式2:if 条件; then 语句; else 语句; fi
[root@xuexi-001 shell]# cp if1.sh if2.sh
[root@xuexi-001 shell]# vi if2.sh
#!/bin/bash
a=1
if [ $a -gt 3 ]
then
echo ok
else
echo nook
fi
[root@xuexi-001 shell]# sh -x if2.sh
+ a=1
+ '[' 1 -gt 3 ']'
+ echo nook
nook
[root@xuexi-001 shell]# sh if2.sh
nook
if语句第三种格式
格式3:if …; then … ;elif …; then …; else …; fi
[root@xuexi-001 shell]# cp if2.sh if3.sh
[root@xuexi-001 shell]# vi if3.sh
#!/bin/bash
a=2
if [ $a -gt 4 ]
then
echo ">1"
elif [ $a -lt 6 ]
then
echo "<6 && >1"
else
echo nook
fi
[root@xuexi-001 shell]# sh if3.sh
<6 && >1
[root@xuexi-001 shell]# sh -x if3.sh
+ a=2
+ '[' 2 -gt 4 ']'
+ '[' 2 -lt 6 ']'
+ echo '<6 && >1'
<6 && >1
[root@xuexi-001 shell]#
逻辑判断表达式
if [ $a -gt $b ] 表示,大于
if [ $a -lt 5 ] 表示,小于
if [ $b -eq 10 ] 表示,等于10
-ne(!=) 表示,不等于
-ge(>=) 表示,大于等于
-le(<=) 表示,小于等于
可以使用 && || 结合多个条件
if [ $a -gt 5 ] && [ $a -lt 10 ]; then
if [ $b -gt 5 ] || [ $b -lt 3 ]; then