Bash while语句 - 无限循环

时间:2013-04-04 15:04:35

标签: bash shell loops if-statement while-loop

#!/bin/bash
CHECKUSER=$(grep "$USER" /var/log/string.log)
if [[ $CHECKUSER == "" ]];
   then
        echo  "Please enter y or n? (y/n)?"
        read string
        if [ "$string" = "y" -o "$string" = "n" ];
           then
              {
              echo "$USER - $string" >> /var/log/string.log
              }
           else
              while [ "$string" != "y" -o "$string" != "n" ];
                 do
                 echo "'$string' is an invalid option, please enter y or n: "
                 read string
              done
        fi
elif [[ $CHECKUSER == "$USER - n" ]];
   then
        echo "User selected n"
elif [[ $CHECKUSER == "$USER - y" ]];
   then
        echo "You've already said that you would like your account backed up."
else echo "User entered something other than y or n"
fi

一切正常!但如果你输入的东西不是y | n,你会陷入无限循环。

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

你必须改变

while [ "$string" != "y" -o "$string" != "n" ];

while [ "$string" != "y" -a "$string" != "n" ];

因为否则它总是如此:

if string="y" ----------> [ false -o true  ] == [ true ]
if string="n" ----------> [ true  -o false ] == [ true ]
if string="whatever" ---> [ true  -o true  ] == [ true ]

答案 1 :(得分:2)

这个while循环中有两个问题:

while [ "$string" != "y" -o "$string" != "n" ];
do
    echo "'$string' is an invalid option, please enter y or n: "
    read backup
done

正如fedorqui所指出的那样,你的测试总是正确的,但即使你修复了,你也要循环,因为你正在阅读备份而不是字符串。把事情改为:

while [ "$string" != "y" -a "$string" != "n" ];
do
    echo "'$string' is an invalid option, please enter y or n: "
    read string
done