由于空格而在while循环中出错

时间:2017-07-28 07:58:30

标签: bash shell

我是这个行业的新手,我遇到了问题...

在我的while循环中,我将用户输入与变量进行比较。 问题是如果用户输入是空格或特殊字符,我无法比较它。 (在If Else中,但我认为while和if的解决方案是相同的) 这是代码,你可以看到它。

var1="therealpass"
counter=0
tries=3
read -sp 'Please enter the password! (3 tries left): ' pass_var

while (( $pass_var != $var1 || $counter < 2 ))
do

if [ $pass_var == $var1 ]
      then
        echo "That was the real password! Good job!"
        break
       else
        counter=$[counter + 1]
        tries=$[tries - 1]

       if [ $tries == 1 ]
        then
            echo
            echo "$tries try left. Please try it again!"
            read -sp 'Password: ' pass_var
            echo
         else
            echo
            echo "$tries tries left. Please try it again!"
            read -sp 'Passwort: ' pass_var
       fi
fi
done

1 个答案:

答案 0 :(得分:1)

你必须引用你的字符串变量。此外,将while循环语法更改为以下内容:while [ "$pass_var" != "$var1" ] && [ $counter -lt 2 ]

您在循环语法中使用的双括号构造用于算术计算。你正在比较字符串。见The Double-Parentheses Construct

条件应该是逻辑AND。在bash中,<表示为-lt,而不是比较。 Operators

你的代码变成这样:

var1="therealpass"
counter=0
tries=3
read -sp 'Please enter the password! (3 tries left): ' pass_var

while [ "$pass_var" != "$var1" ] && [ $counter -lt 2 ]
do

if [ "$pass_var" == "$var1" ]
  then
    echo "That was the real password! Good job!"
    break
   else
    counter=$[counter + 1]
    tries=$[tries - 1]

   if [ $tries == 1 ]
    then
        echo
        echo "$tries try left. Please try it again!"
        read -sp 'Password: ' pass_var
        echo
     else
        echo
        echo "$tries tries left. Please try it again!"
        read -sp 'Passwort: ' pass_var
   fi
fi
done

进一步阅读:Conditional Statements