0
#!/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

This all works fine! But if you enter something other than y|n you get stuck in an infinite loop.

Any ideas?

3
  • set -xv added to the script to turn on debug tracing is often very helpful for figuring out what you did wrong. Commented Apr 4, 2013 at 19:26
  • FYI: If you put do and then on the next line as you do (and as I do, give or take the indentation), then you don't need the semicolon at the end of the previous line. The semicolons are necessary when the do and then is on the same line as the test. Commented Apr 4, 2013 at 23:13
  • @JonathanLeffler Cheers! I will take note. Commented Apr 5, 2013 at 10:27

2 Answers 2

4

You have to change

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

to

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

Because otherwise it is always true:

if string="y" ----------> [ false -o true  ] == [ true ]
if string="n" ----------> [ true  -o false ] == [ true ]
if string="whatever" ---> [ true  -o true  ] == [ true ]
Sign up to request clarification or add additional context in comments.

3 Comments

Cheers fedorqui! Something so simple was bugging me for hours!
Although, if i type in something other than y/n and then type in y/n afterwards it doesnt do this line echo "$USER - $string" >> /var/log/string.log
Fixed this by moving the while before the if.
2

You have two problems in this while loop:

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

As fedorqui pointed out, your test is always true, but even if you fix that you are going to loop because you are reading into backup and not string. Change things to:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.