0

I'm new in this business and I've got a problem...

In my while-loop I compare an user input with a variable. The problem is if the user input is a space or a special charakter I cant compare it. (In the If Else too but I think the solution for while and if else is the same) Here is the code so you can see it.

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
CanLo
  • 35
  • 5

1 Answers1

1

You have to quote your string variables. In addition, change your while loop syntax to the following: while [ "$pass_var" != "$var1" ] && [ $counter -lt 2 ]

The double parenthesis constructs that you were using in your loop syntax are for arithmetic evaluations. You are comparing strings. See The Double-Parentheses Construct

The condition should be a logical AND. In bash, < is expressed as -lt for less than comparison. Operators

You code becomes something like this:

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

Further reading: Conditional Statements

yogur
  • 810
  • 10
  • 19
  • Thank you very much! I read that I need the ((, but I think I missunderstood that. Thank you! – CanLo Jul 28 '17 at 08:39
  • But if we change < to "-lt" why we dont change != to "-ne" ? – CanLo Jul 28 '17 at 08:45
  • @CanLotoz In bash, string comparison operators are different than that of numbers. `!=` is used to compare strings while `-ne` is used to compare numbers. – yogur Jul 28 '17 at 08:50