Shell学习笔记 - 分支语句
一、单分支if语句
- 语法格式
复制代码
if [ 条件判断式 ]; then
程序
fi
或者
if [ 条件判断式 ]
then
程序
fi
注意:中括号和条件判断式之间必须有空格
复制代码
- 示例1:判断登陆的用户是否是root
复制代码
#!/bin/bash
if [ “$USER” == root ];then
echo “Login User is root”
fi
#########或者#########
#!/bin/bash
if [ “$USER” == root ]
then
echo “Login User is root”
fi
复制代码
- 示例2:判断分区使用率
复制代码
#!/bin/bash
test=$(df -h | grep sda1 | awk ‘{print $5}’ | cut -d ‘%’ -f 1)
if [ $test -ge 90 ];then
echo “Warning! /dev/sda1 is full!”
fi
复制代码
二、双分支if语句
- 语法格式
复制代码
if [ 条件判断式 ]; then
条件成立时,执行的程序
else
条件不成立时,执行的程序
fi
或者
if [ 条件判断式 ]
then
条件成立时,执行的程序
else
条件不成立时,执行的程序
fi
复制代码
- 示例1:输入一个文件,判断是否存在
复制代码
#!/bin/bash
read -p “Please input a file:” file
if [ -f $file ]; then
echo “File: $file exists!”
else
echo “File: $file not exists!”
fi
复制代码
- 示例2:判断apache服务是否启动了,如果没有启动,就代码启动
复制代码
#!/bin/bash
test=$(ps aux | grep httpd | grep -v ‘grep’ | wc -l)
if [
t
e
s
t
−
g
t
0
]
;
t
h
e
n
e
c
h
o
"
test -gt 0 ]; then echo "
test−gt0];thenecho"(date) httpd is running!"
else
echo “$(date) httpd isn’t running, will be started!”
/etc/init.d/httpd start
fi
复制代码
三、多分支if语句
-
语法格式
复制代码
if [ 条件判断式1 ]; then
当条件判断式1成立时,执行程序1
elif [ 条件判断式2 ]; then
当条件判断式2成立时,执行程序2
…省略更多条件…
else
当所有条件都不成立时,最后执行此程序
fi
复制代码 -
示例:实现计算器
复制代码
#!/bin/bash
输入数字a,数字b和操作符
read -p “Please input number a:” a
read -p “Please input number b:” b
read -p “Please input operator[+|-|*|/]:” opt
判断输入内容的正确性
testa=$(echo a ∣ s e d ′ s / [ 0 − 9 ] / / g ′ ) t e s t b = a | sed 's/[0-9]//g') testb= a∣sed′s/[0−9]//g′)testb=(echo a ∣ s e d ′ s / [ 0 − 9 ] / / g ′ ) t e s t o p t = a | sed 's/[0-9]//g') testopt= a∣sed′s/[0−9]//g′)testopt=(echo $opt | sed ‘s/[+|-|*|/]//g’)
if [ -n “
t
e
s
t
a
"
−
o
−
n
"
testa" -o -n "
testa"−o−n"testb” -o -n “
t
e
s
t
o
p
t
"
]
;
t
h
e
n
e
c
h
o
"
i
n
p
u
t
c
o
n
t
e
n
t
i
s
e
r
r
o
r
!
"
e
x
i
t
1
e
l
i
f
[
"
testopt" ]; then echo "input content is error!" exit 1 elif [ "
testopt"];thenecho"inputcontentiserror!"exit1elif["opt” == “+” ]; then
result=
(
(
((
((a+
b
)
)
e
l
i
f
[
"
b)) elif [ "
b))elif["opt" == “-” ]; then
result=
(
(
((
((a-
b
)
)
e
l
i
f
[
"
b)) elif [ "
b))elif["opt" == "" ]; then
result=
(
(
((
((a
b
)
)
e
l
s
e
r
e
s
u
l
t
=
b)) else result=
b))elseresult=((
a
/
a/
a/b))
fi
echo “a $opt b = $result”
复制代码
四、case语句
case语句和if…elif…else语句都是多分支条件语句,不过和if多分支条件语句不同的是,case语句只能判断一种条件关系,而if语句可以判断多种条件关系。
-
语法格式
复制代码
case $变量名 in
“值1”)
如果变量的值等于值1,则执行程序1
;;
“值2”)
如果变量的值等于值2,则执行程序2
;;
…省略其他分支…
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
复制代码 -
示例:判断用户输入
复制代码
#!/bin/bash
read -p “Please choose yes/no:” cmd
case $cmd in
“yes”)
echo “Your choose is yes!”
;;
“no”)
echo “Your choose is no!”
;;
*)
echo “Your choose is error!”
;;
esac