Bash: 为什么包含字符串 a 的变量在 if 语句中等于字符串 b?

Bash: Why does variable containing string a equate to string b in an if statement?

我设置了提示以获取用户输入 Yy/Nn。然后我检查响应是否匹配 Y/y 或 N/n。然而,每次它在“$prompt_1”="Y"/"y" 上的计算结果为真,即使您回答 N/n。现在我确定这是有原因的,但是四处搜索让我找到了一些解决方案 IG:围绕变量的 Qoutes。但是没有任何帮助解决这个问题。


#!/bin/bash



clear;
echo "Would you like to proceed with installation?"
read prompt_1;

echo $prompt_1;

if [ "$prompt_1"="Y" ] || [ "$prompt_1"="y" ]; then
  echo "You've accepted installation";


elif [ "$prompt_1”="N"] || [ “$prompt_1"="n" ]; then
  exit;
fi


您需要在 = 运算符周围添加空格:

if [ "$prompt_1" = "Y" ] || [ "$prompt_1" = "y" ]; then
  echo "You've accepted installation";
elif [ "$prompt_1" = "N" ] || [ "$prompt_1" = "n" ]; then
  exit;
fi

或者在 [[...]] 表达式中使用模式匹配运算符 =~

if [[ "$prompt_1" =~ ^[Yy]$ ]]; then
    echo "You've accepted installation";
elif [[ "$prompt_1" =~ ^[Nn]$ ]]; then
    exit
fi

case语句解决方案。

case $prompt_1 in
  [Yy]) echo "You've entered $prompt_1 and accepted installation."
  ##: do something here 
  ;;
  [Nn]) echo "You entered $prompt_1 and did not accepted the installation."
   exit
   ;;
  *|'') echo "Unknown option ${prompt_1:-empty}."  ##: not [Nn] or [Yy] or empty.
   exit
  ;;
esac
  • 这不再局限于 bash,它应该也适用于其他 POSIX sh shell。

另一个建议,使用 case 和小写替换:

case ${prompt_1,,} in
    y|yes|"just do it")
        echo "You've accepted installation"
        # perform installation
        ;;
    n|no|forget) exit;;
    *) echo "Wrong answer, try again";;
esac

PS:适用于 bash4 或更高版本。