条件判断式的使用
if then
只有一个判断式
if [条件判断式];then
...... //符合if条件的在这里执行
fi //返回来写结束if判断之意
多个条件
放在一个[ ]里
[a -o b] [a -a b]
-o or
-a and
放在多个[ ]里
[a] && [b]
[a] || [b]
&& 代表 and
|| 代表 or
read -p "please input (Y/N):" yn
if [ "$yn" == "Y" -o "$yn" == "y" ];then
echo -e "OK,Continue"
exit 0
fi
if [ "$yn" == "N" -o "$yn" == "n" ];then
echo -e "OK,Interrupt"
exit 0
fi
echo -e "I dont't know what your choices" && exit 0
注意:
[ ]中两侧和各个条件之间加 空格
if 需要结束符号 fi 倒写过来
多重、复杂条件判断
一个条件的判断
#一个条件判断,分成功与失败进行
if []; then
...... 条件成立时,执行的程序
else
...... 条件失败时,执行的程序
fi
多个条件的判断
#更多条件参与判断,分多种情况执行
if [1]; then
...... 符合1,执行
elif [2]; then
...... 符合2,执行
else
...... 1和2都不符合,执行
fi
实验代码
if [ "$1" == "hello" ];then
echo -e "Hello,How are you?"
elif [ "$1" == "" ];then
echo -e "You must input parameters,ex> {$0 someword}"
else
echo -e "The only parameter is hello, ex> {$0 hello}"
fi
利用case
#使用方式
case $变量名 in
"1")
...... #满足第一个条件
;;
"2")
...... #满足第二个条件
;;
"*")
exit 1 #不满足上述任何条件
;;
esac
实验代码
case $1 in
"one")
echo " your choice is one"
;;
"two")
echo "your choice is two"
;;
"three")
echo "your choice is three"
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
使用function的功能
#语法
function fname(){
......
}
实验代码
function printit(){
echo -n "Your choice is ";
}
# read -p "Input your choice:" choice
# case $choice in
echo "This program will print your selection !"
case $1 in
"one")
printit;echo $1 | tr 'a-z' 'A-Z'
;;
"two")
printit;echo $1 | tr 'a-z' 'A-Z'
;;
"three")
printit;echo $1 | tr 'a-z' 'A-Z'
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
注意,
shell是自上而下,自左而右执行的,所以function的声明必须放在最前面,否则会在调用的时候报找不到function的错误。
function的内建参数
和shell脚本的默认参数类似
$0代表函数名,$1,$2, 3 ⋅ ⋅ ⋅ ⋅ ⋅ 3····· 3⋅⋅⋅⋅⋅#依次类推
使用的时候,不能和shell脚本的默认参数混淆
实验代码
function printit(){
echo "Your choice is $1";
}
# read -p "Input your choice:" choice
# case $choice in
echo "This program will print your selection !"
case $1 in
"one")
printit 1
;;
"two")
printit 2
;;
"three")
printit 3
;;
*)
echo "Usage $0 {one|two|three}"
;;
esac
注意:
case 后面的 $1 指执行脚本的时候紧跟的第一个参数
printit 里面的$1 指调用它紧跟的参数,这里指 1 2 3