1. if条件判断
if条件判断:
if [ 条件 ]; then
do something
fi
多个条件:
&& 代表AND
|| 代表OR
多重判断:
if [ 条件 ];then
do something
elif [ 条件2 ]; then
//do something
else
//do someshing
fi
#!/bin/bash
read -p "Please input (Y/N) : " yn
if [ "$yn" == "Y" ] || [ "$yn" == "y" ]; then
echo "Yes!"
elif [ "$yn" == "N" ] || [ "$yn" == "n" ]; then
echo "No!"
else
echo "Input Error"
fi
exit 0
查看运行结果
[work@www sh]$ sh hello.sh
Please input (Y/N) : y
Yes!
[work@www sh]$ sh hello.sh
Please input (Y/N) : l
Input Error
[work@www sh]$
2. case判断
如果if中判断层级比较多,建议使用case, 否则嵌套太多,代码易读性变差。
case的语法
case $变量名称 in
“变量1”)
do something
;; 每个结尾用两个分号
“变量2”)
do something
;;
*) 最后一个*代表其他值
do something
;;
esac
看下面例子:
#!/bin/bash
case $1 in
"one")
echo "One"
;;
"two")
echo "Two"
;;
*)
echo "Usage $0 (one|two)"
;;
esac
exit 0
运行结果
[work@ww sh]$ sh hello.sh
Usage hello.sh (one|two)
[work@www sh]$ sh hello.sh one
One
[work@www sh]$