You need to enable JavaScript to run this app. 编写Linux bash脚本时if条件判断异常,选择yes反复输出==yes如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

编写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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 11:45:03