LInux shell入门 --- 逻辑判断和分支
Shell结构化语言
在Linux Shell中,0代表Yes、True;非0代表No、Falseif判断:
如果condition是true,或者condition的退出状态值(exit status)是0,执行command命令
if condition then
command
elif condition1 then
command1
else
commandn
fi
for循环(循环内部使用$变量名、如$i来引用循环变量、其实就是使用$来引用变量的值):
for (( expr1; expr2; expr3 ))或者
for { variable name } in { list }
do
command
done
while循环
while [ condition ]
do
command
done
case判断(可以用来替代多层次if-else循环)
case $variable-name in
pattern1) command
command;;
pattern2) command
command;;
patternN) command
command;;
*) command
command;;
esac
判断运算符数学运算符:-eq(is equal to),-ne(is not equal to),-lt(is less than),-le(is less than or equal to),-gt(is greater than),-ge(is greater than or equal to)
字符串比较运算符:string1 = string2,string1 != string2,string1(string1 is NOT NULL or not defined ),-n string1(string1 is NOT NULL and does exist),-z string1(string1 is NULL and does exist)
文件、文件夹判断运算符:-s file (Non empty file),-f file (Is File exist or normal file and not a directory ),-d dir(Is Directory exist and not a file),-w file(Is writeable file),-r file(Is read-only file),-x file(Is file is executable)
逻辑运算符:! Expression(Logical NOT),expression1 -a expression2(Logical AND),expression1 -o expression2(Logical OR)
For test statement with if command:
if test 5 -eq 6
if test 5 -ne 6
if test 5 -lt 6
if test 5 -le 6
if test 5 -gt 6
if test 5 -ge 6
For [ expr ] statement with if command
if [ 5 -eq 6 ]
if [ 5 -ne 6 ]
if [ 5 -lt 6 ]
if [ 5 -le 6 ]
if [ 5 -gt 6 ]
if [ 5 -ge 6 ]