人生总是充满选择,每一刻,都决定你的成功与失败。
SHELL=[ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 ]
progress:[########## ] 50%
Ax Shell Decision Making | 抉择
shell支持条件语句,通过不同的条件执行不同的操作。
两种条件判断的声明:
- The if…else statement
- The case…esac statement
The if…else statements
从给定的选项中选定一个。
- if…fi statement
- if…else…fi statement
- if…elif…else…fi statement
if…fi statement
基本的条件判断语句,允许有条件的语句执行。条件为true则执行,false不执行任何语句。
语法
if [ expression ]
then
Statement(s) to be executed if expression is true
fi
空格很重要,没有空格会出现错误。
如果表达式为命令,命令执行成功则为0,布尔值为true则为true。
例
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
if [ $a != $b ]
then
echo "a is not equal to b"
fi
执行脚本 −
a is not equal to b
The if…else…fi statement
这种方式是受控制的,并执行正确的语句。
语法
if [ expression ]
then
Statement(s) to be executed if expression is true
else
Statement(s) to be executed if expression is not true
fi
例
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
执行脚本 −
a is not equal to b
The if…elif…fi statement
这是if语句的高级形式,允许多个条件,并作出正确的决策。
语法
if [ expression 1 ]
then
Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
Statement(s) to be executed if expression 3 is true
else
Statement(s) to be executed if no expression is true
fi
这个形式就是存在多个if语句,如果都不为真,则执行else块。
例
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
执行脚本 −
a is less than b
The case…esac Statement
如果存在多个条件的情况下,case…esac是一个很好的选择,它比if…elif更加的简洁。只有一种形式:
语法
根据表达式的来执行不同的语句。
case word in
pattern1)
Statement(s) to be executed if pattern1 matches
;;
pattern2)
Statement(s) to be executed if pattern2 matches
;;
pattern3)
Statement(s) to be executed if pattern3 matches
;;
*)
Default condition to be executed
;;
esac
字符串中的值与每个情况进行比较,直到匹配,如果都没有,则退出,不执行任何操作。
没有最大的情况,最少一个。
当执行语句部分时,;;
命令将流跳到esac末尾来结束判断的匹配。类似C语言的break。
例1
#!/bin/sh
FRUIT="kiwi"
case "$FRUIT" in
"apple") echo "Apple pie is quite tasty."
;;
"banana") echo "I like banana nut bread."
;;
"kiwi") echo "New Zealand is famous for kiwi."
;;
esac
执行脚本 −
New Zealand is famous for kiwi.
例2
这个例子很好的演示了用于命令行参数。
#!/bin/sh
option="${1}"
case ${option} in
-f) FILE="${2}"
echo "File name is $FILE"
;;
-d) DIR="${2}"
echo "Dir name is $DIR"
;;
*)
echo "`basename ${0}`:usage: [-f file] | [-d directory]"
exit 1 # Command to come out of the program with status 1
;;
esac
执行脚本 −
$./test.sh
test.sh: usage: [ -f filename ] | [ -d directory ]
$ ./test.sh -f index.htm
$ vi test.sh
$ ./test.sh -f index.htm
File name is index.htm
$ ./test.sh -d unix
Dir name is unix
$