Error in a while-loop because of a space
本问题已经有最佳答案,请猛点这里访问。
我是这个行业的新人,有问题…
在while循环中,我比较用户输入和变量。问题是,如果用户输入是一个空格或一个特殊字符,我就无法进行比较。(在if-else中也是,但我认为暂时的解决方案和if-else是相同的)这是代码,你可以看到它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 |
您必须引用字符串变量。另外,将while循环语法更改为以下内容:
在循环语法中使用的双括号结构用于算术计算。您正在比较字符串。参见双括号结构
条件应该是逻辑和。在bash中,
你的代码变成这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | 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 |
进一步阅读:条件陈述