|
做为运维人员来讲,写脚本是最基本的功底了,脚本写的得好,意味着我们很多工作可以通过编程来轻松的实现,同时也大大减少了我们执行重复性动作的工作。当然写脚本也不是一件多难的事情,只要我们基本命令学的熟练,再把脚本语法掌握好,能通过脚本去完成的动作我们尽量去写脚本实现,久而久之,我们也就成了一个脚本高手了,手上累积的脚本多了,想去完成曾经执行过的动作时,直接调用我们曾经用过的脚本,就可以轻松帮我们完成许多重复性的工作了,同时也就以为着我们的运维工作越来越顺手,越来越轻松了。今天我为大家分享的是关于如何用if语句去写一些选择执行的脚本。
条件选择if语句(选择执行)
注意:if语句可嵌套
(一)单分支
if 判断条件;then
条件为真的分支代码
fi
示例代码:
1 #!/bin/bash
2
3 #Author:wangjun
4 #Version:1.0
5 #Create time:2016-08-13 19:40:55
6 #Description:ifsingle test
7
8 read -p "Please input a username : " name
9 if>
10 echo "$name user exists,user> 11 fi
执行过程如图所示:
(二)双分支
if 判断条件; then
条件为真的分支代码
else
条件为假的分支代码
fi
示例代码:
1 #!/bin/bash
2
3 #Author:wangjun
4 #Version:1.0
5 #Create time:2016-08-13 20:00:00
6 #Description:ifdouble test
7
8 read -p "Please input a username : " name
9 if>
10 echo "$name user exists,user> 11 else
12 echo "$name user doesn't exist"
13 fi
执行过程如图所示:
(三)多分支
if CONDITION1; then
if-true
elif CONDITION2; then
if-ture
elif CONDITION3; then
if-ture
...
else
all-false
fi
逐条件进行判断,第一次遇为“真”条件时,执行其分支,而后结束整个if语句
示例代码:
1 #!/bin/bash
2
3 #Author:wangjun
4 #Version:1.0
5 #Create time:2016-08-13 20:22:16
6 #Description:ifmultiple test
7
8 read -p "Please input you age : " age
9 if [ "$age" -gt 0 -a "$age" -lt 18 ];then
10 echo "Underage,please quit"
11 elif [ "$age" -ge 18 -a "$age" -le 55 ];then
12 echo "Adults ,please enter"
13 elif [ "$age" -gt 55 -a "$age" -le 110 ];then
14 echo "Old people,please take care of your body"
15 elif [ "$age" -gt 110 ];then
16 echo "You are an alien"
17 else
18 echo "You haven't been born yet"
19 fi
执行过程如图所示:
写的比较详细,执行过程的帖图也全部给出来了,相信大家一定看的明白,如果觉得我写的博文对你有帮助,请为我点个赞,给我一些精神鼓励,我会更加努力的!
|
|
|