使用结构化命令
1.使用if-then语句
格式如下:
if commands
then
commands
fi
bash shell的if语句会运行if后面的那个命令,如果该命令的退出状态
码为0,则执行then后面的命令,如果状态码是其他值,则if-then语句
就到此结束
2.if-then-else语句
if command
then
commands
else
commands
fi
前面的if-then使用规则一样,只是当if后面的command不为0时,则执行
ele后面的命令
3.嵌套if
if command1
then
command
elif command2
then
command
.
.
.
elif comandn
then
command
fi
每个then后面当然可以多条命令,shell会将他视为一个块
4.test命令
test命令提供了在if-then语句中测试不同条件的途径。如果test
命令中列出的条件成立,test命令就会退出并返回退出状态码0
列如:
#!/bin/bash
my_variable="Full"
if test $my_variable
then
echo "The $my_variable expression returns a True"
else
echo "False"
fi
这样在shell中执行,会输出The Full expression returns a True
test命令可以判断三类条件
数值比较
字符串比较
文件比较
bash shell 提供了另外一种条件测试方法
if [ condition ]
then
commands
fi
5.数值比较
n1 -eq n2 检查n1是否等于n2
-ge 大于或等于
-gt 大于
-le 小于或等于
-lt 小于
-ne 不等于
#!/bin/bash
value1=10
if[ $value1 -gt 5]
then
echo "The test value $value1 is greater than 5"
fi
输出The test value 10 is greater than 5
6.字符串比较
str1 = str2 检查str1与str2是否相同
等等
-n str1 检查str1长度是为非0
-z str1 检查str1长度是否为0
注意这些比较仅针对第一个字母
#!/bin/bash
str1="Full"
str2="Full2"
if[ $str1 -eq $str2]
then
echo "euqal"
fi
输出euqal
7.文件比较
test –b File 文件存在并且是块设备文件
test –c File 文件存在并且是字符设备文件
test –d File 文件存在并且是目录
test –e File 文件存在
test –f File 文件存在并且是正规文件
test –g File 文件存在并且是设置了组ID
test –w File 文件存在并且可写
test –r File 文件存在并且可读
test –x File 文件存在并且可执行
8.case命令
case variable in
pattern1)
command;;
pattern2)
command;;
pattern3)
command;;
*)
command;;
esac