前言
在Shell脚本中,可以使用if语句和case语句来进行条件判断和分支控制,类似于其他编程语言中的if-else和switch语句。以下是示例代码介绍:
1. if语句的使用:
if [ condition1 ]; then
# code to execute when condition1 is true
elif [ condition2 ]; then
# code to execute when condition2 is true
else
# code to execute when all conditions are false
fi
condition1
、condition2
是需要评估的表达式,可以使用比较运算符和逻辑运算符构建条件判断。elif和else是可选的。
2. case语句的使用:
case $variable in
pattern1)
# code to execute when variable matches pattern1
;;
pattern2)
# code to execute when variable matches pattern2
;;
*)
# code to execute when variable does not match any pattern
;;
esac
variable
是需要匹配的变量,pattern1
、pattern2
是通配模式,可以使用 *
、?
、[...]
等进行匹配。;;
表示匹配成功后结束该分支的执行。
3. 示例代码
结合if和case的示例代码,用于展示如何使用条件判断和分支控制:
#!/bin/bash
fruit="apple"
if [ $fruit == "banana" ]; then
echo "It is a banana"
elif [ $fruit == "apple" ]; then
echo "It is an apple"
else
echo "It is neither a banana nor an apple"
fi
case $fruit in
"banana")
echo "It is a banana"
;;
"apple")
echo "It is an apple"
;;
*)
echo "It is neither a banana nor an apple"
;;
esac
运行以上脚本将输出:
It is an apple
It is an apple