【问题标题】:IF Statement triggering without true statement [duplicate]没有真实语句的IF语句触发[重复]
【发布时间】:2017-10-13 09:47:36
【问题描述】:

以下 while 循环旨在不断询问用户输入,直到输入指定的“中断”字符。但是,出于某种原因,无论输入什么文本,都会触发此 IF 语句。

 while true; do
    #Prompt user for Input
    printf "Please insert value. Insert the letter 'D' when you are done\n";
    #Read User Input
    read User_Input;
    echo "DEBUG: Input is: $User_Input";
    #Check User Input for Break Command
        if [ "$User_Input"=="D" ]; then
            break
        fi

done

在脚本中,我将用户输入变量声明为User_Input="";

据我所知,if 语句是正确的,并且脚本在运行时没有抛出任何错误。

【问题讨论】:

  • 如果您阅读the Bash manual page,您将看到== 运算符是用于双括号表达式(即在[[ ... ]] 中)的特定于Bash 的扩展。对于单括号,您应该阅读the test manual page

标签: bash


【解决方案1】:
if [ "$User_Input"=="D" ]; then

DEBUG: Input is: a
+ '[' a==D ']'
+ break

应该写成

if [ "$User_Input" == "D" ]; then

DEBUG: Input is: e
+ '[' e == D ']'
+ true
+ printf 'Please insert value. Insert the letter '\''D'\'' when you are done\n'
Please insert value. Insert the letter 'D' when you are done
+ read User_Input
D
+ echo 'DEBUG: Input is: D'
DEBUG: Input is: D
+ '[' D == D ']'
+ break

==前后需要空格

【讨论】:

    【解决方案2】:

    来自

    if [ "$User_Input"=="D" ]; then
    

    # space
    if [ "$User_Input" == "D" ]; then
    

    因为它调用带有4 参数的命令。

    正如 bash 内置函数的手册页所述:“每个运算符和操作数 必须是一个单独的参数。”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-07
      • 2014-03-15
      • 1970-01-01
      • 2020-09-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2012-07-06
      相关资源
      最近更新 更多