您的位置:首页 > 运维架构 > Shell

Shell 流程控制

2018-01-20 20:57 501 查看

判断语句 if

格式1

语法:

if 条件 ;then commond;fi

eg:

#!/bin/bash
a=5
if [ $a -gt 3 ]
then
echo "大于3"
fi


格式2

语法:

if 条件1;then commond1;else commond2;fi

eg:

#!/bin/bash
a=5
if [ $a -gt 3 ]
then
echo "大于3"
else
echo "不大于3"
fi


格式3

语法:

if 条件1;then commond1;elif 条件2;then commond2;else commond3;fi

eg:

#!/bin/bash
a=5
if [ $a -lt 3 ]
then
echo "a<3"
elif [ $a -gt 6 ]
then
echo "a>6"
else
echo "Out of the zone"
fi


if 特殊用法

if [ -z “$a” ]:表示当变量a的值为空时;

if [ -n “$a” ]:表示当变量a的值不为空时;

eg:

#!/bin/bash
n=`wc -l /tmp/test.txt`
if [ $n -gt 20 ]
then
echo 1
else
echo 0
fi


在该脚本中无语法错误,只是我们预设/tmp/test.txt是存在的,如果该文件不存在,该脚本执行的时候就会报错:

[root@dl-001 sbin]# sh  if.sh
wc: /tmp/test.txt: 没有那个文件或目录
if.sh: 第 3 行:[: -gt: 期待一元表达式


所以,为了避免这种错误的发生,需要将脚本写的更加严谨,需要在执行“if [ $n -gt 20 ]”之前先确认文件“/tmp/test.txt”是否存在:

#!/bin/bash
n=`wc -l /tmp/test.txt`
if [ -z $n ]
then
echo "error"
exit
elif [ $n -lt 20 ]
then
echo 1
else
echo 0
fi


即,如果变量n为空则显示error并退出该脚本。

[root@dl-001 sbin]# sh  if.sh
wc: /tmp/test.txt: 没有那个文件或目录
error


即,当该文件不存在的时候就会退出执行,不会提示存在语法错误。

eg:

#判断某参数存在:
[root@dl-001 sbin]# vim if1.sh
#!/bin/bash
if
grep -wq 'user1' /etc/passwd
then
echo "user1 exist."
fi
[root@dl-001 sbin]# sh if1.sh

#判断某参数不存在:
[root@dl-001 sbin]# vim if2.sh
#!/bin/bash
if
! grep -wq 'user1' /etc/passwd
then
echo "no user1"
fi
[root@localhost sbin]# sh if2.sh
no user1


说明: grep中-w选项=Word,表示过滤一个单词;-q,表示不打印过滤的结果。判断某参数不存在时使用!表示取反。

case判断

格式:

case 变量名 in
value1)
commond1
;;
value2)
commod2
;;
value3)
commod3
;;
esac


在case中,可以在条件中使用“|”,表示或的意思,如:

2|3)        //表示2或者3
commond
;;


小练习(需求:输入考试成绩,判断考试成绩的等级)

[root@dl-001 sbin]# vim case1.sh
#!/bin/bash
read -p "Please input a number: " n
if [ -z "$n" ]
then
echo "Please input a number."
exit 1
#“exit 1”表示执行该部分命令后的返回值
#即,命令执行完后使用echo $?的值
fi

n1=`echo $n|sed 's/[0-9]//g'`
#判断用户输入的字符是否为纯数字
#如果是数字,则将其替换为空,赋值给$n1
if [ -n "$n1" ]
then
echo "Please input a number."
exit 1
#判断$n1不为空时(即$n不是纯数字)再次提示用户输入数字并退出
fi

#如果用户输入的是纯数字则执行以下命令:
if [ $n -lt 60 ] && [ $n -ge 0 ]
then
tag=1
elif [ $n -ge 60 ] && [ $n -lt 80 ]
then
tag=2
elif [ $n -ge 80 ]  && [ $n -lt 90 ]
then
tag=3
elif [ $n -ge 90 ] && [ $n -le 100 ]
then
tag=4
else
tag=0
fi
#tag的作用是为判断条件设定标签,方便后面引用
case $tag in
1)
echo "not ok"
;;
2)
echo "ok"
;;
3)
echo "ook"
;;
4)
echo "oook"
;;
*)
echo "The number range is 0-100."
;;
esac


执行结果:

[root@dl-001 sbin]# sh case1.sh
Please input a number: 90
oook
[root@dl-001 sbin]# sh case1.sh
Please input a number: 80
ook
[root@dl-001 sbin]# sh case1.sh
Please input a number: 60
ok
[root@dl-001 sbin]# sh case1.sh
Please input a number: 55
not ok
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell 流程控制