如何在bash中创建多个“if”函数?例如,我想做这样的事情:
if [ "$answer" == "0" ]; then 0
if [ "$answer" == "1" ]; then 1
if [ "$answer" == "2" ]; then 2
else echo "error"
fi
由于
答案 0 :(得分:6)
如果您想使用相同的测试("$answer" ==
),那么使用case
会更好:
case "$answer" in
0) echo "0" ;;
1) echo "1" ;;
2) echo "2" ;;
3|4) echo "3 or 4" ;;
*) echo "error" ;;
esac
你可以在这里找到许多关于Bash脚本的有价值的东西:
man bash
答案 1 :(得分:2)
您可以使用elif
if [ "$answer" == "0" ]; then echo "0"
elif [ "$answer" == "1" ]; then echo "1"
elif [ "$answer" == "2" ]; then echo "2"
else echo "error"
fi