Linux脚本while循环如何匹配Y、Yes、y等多种用户肯定输入
你原来的写法报错是因为[]对应的test命令不支持逗号分隔的多值匹配语法,正确实现可以用以下几种方案:
方案1:兼容所有POSIX shell的多条件判断
用-o(逻辑或)拼接多个匹配条件,注意输入变量要加双引号避免空值报错:
echo -e "Would you like to run the script? (Y or N): \c" read ans while [ "$ans" = "Y" -o "$ans" = "y" -o "$ans" = "Yes" -o "$ans" = "yes" ] do # 脚本逻辑 done
如果还要兼容大小写混写的输入比如yEs、YeS这类,可以先把输入统一转为小写再判断,逻辑更简洁:
echo -e "Would you like to run the script? (Y or N): \c" read ans # 将输入转为全小写 ans_lower=$(echo "$ans" | tr '[:upper:]' '[:lower:]') while [ "$ans_lower" = "y" -o "$ans_lower" = "yes" ] do # 脚本逻辑 done
方案2:Bash环境下的正则匹配写法
如果你的脚本确定跑在Bash环境下,可以用[[ ]]的正则匹配语法简化写法:
echo -e "Would you like to run the script? (Y or N): \c" read ans # ^匹配字符串开头,$匹配结尾,|分隔多个匹配项 while [[ "$ans" =~ ^(Y|y|Yes|yes)$ ]] do # 脚本逻辑 done
如果要兼容任意大小写的肯定输入,还可以写得更灵活,只要是y开头的输入都判定为同意:
echo -e "Would you like to run the script? (Y or N): \c" read ans # ${ans,,}是Bash 4.0+支持的变量转全小写语法,y*匹配所有y开头的字符串 while [[ "${ans,,}" == y* ]] do # 脚本逻辑 done
方案3:用case语句分支判断
如果后续还要加其他输入分支的处理逻辑,用case语句结构更清晰:
echo -e "Would you like to run the script? (Y or N): \c" read ans case "$ans" in [Yy]|[Yy][Ee][Ss]) while : do # 脚本逻辑 done ;; *) echo "用户未同意,退出脚本" exit 0 ;; esac
内容的提问来源于stack exchange,提问作者Michael Debo
相关产品推荐
相关产品推荐

