编写Linux bash脚本时if条件判断异常,选择yes反复输出==yes如何解决?
Bash脚本if判断异常问题修复
问题原因
你编写的条件判断语法不符合Bash的[[测试结构规范:[[与后续判断表达式之间、]]与前面的判断表达式之间必须保留空格,你代码中的[["$Response"和"Y"]]缺少必要空格,会被Bash识别为无效命令,最终导致逻辑运行异常。
修复后的可用代码
echo "Found a previously saved file. Do you want to continue with this? (Yes/No)" read Response if [[ "$Response" == "Yes" || "$Response" == "yes" || "$Response" == "y" || "$Response" == "Y" ]]; then echo "Success" else echo "Fail" fi
可选优化方案
- 统一将输入转为小写判断,减少重复的判断分支:
echo "Found a previously saved file. Do you want to continue with this? (Yes/No)" read Response # ${Response,,} 会将变量内容全部转为小写 if [[ "${Response,,}" =~ ^(yes|y)$ ]]; then echo "Success" else echo "Fail" fi
- 开启Bash不区分大小写匹配选项,简化判断逻辑:
echo "Found a previously saved file. Do you want to continue with this? (Yes/No)" read Response shopt -s nocasematch if [[ "$Response" == "yes" || "$Response" == "y" ]]; then echo "Success" else echo "Fail" fi # 关闭不区分大小写匹配,恢复默认行为 shopt -u nocasematch
内容的提问来源于stack exchange,提问作者Bipul Dey
相关产品推荐
相关产品推荐

