2

So I am having a problem understanding how to loop a condition. Here is my example:

#!/bin/bash
echo " Which team do you prefer, FSU or UF?"
read -r TEAM
while [ "$TEAM" != "FSU" || "UF" ]; do
        echo "That was not one of your choices. Please choose FSU or UF"
if [ "$TEAM" == "FSU" ]; then
        echo "You chose the better team"
else [ "$TEAM" == "UF" ];
        echo "You did NOT choose the better team"
fi
done

Basically, what I am looking for is user input and if that condition isn't met it would loop back until the correct input is met. What am I doing wrong? In this example I get an error back if I choose an input outside of FSU or Uf as:

"./test.sh: line 4: [: missing `]' ./test.sh: line 4: UF: command not found"

However, if I choose FSU or UF I get the same error.

t3kg33k
  • 41
  • 2
  • 7
  • `[ "$TEAM" != "FSU" || "UF" ]` is not a valid syntax. You have to compare `$TEAM` against each possible string – fedorqui Dec 02 '16 at 14:20
  • The major problem is the while line should read `while [ "$TEAM" != "FSU" || "$TEAM" != "UF" ]; do`. Other than that, you are terminating your loop (`done`) at the wrong place. – Phylogenesis Dec 02 '16 at 14:20
  • Thirdly, looking at [this page](https://en.wikipedia.org/wiki/Florida%E2%80%93Florida_State_football_rivalry#Game_results), it seems the results of your `if` clause are backwards, too. – Phylogenesis Dec 02 '16 at 14:26

1 Answers1

1

Fixed Script:

#!/bin/bash
echo " Which team do you prefer, FSU or UF?"
read -r TEAM
while [[ "$TEAM" != "FSU" && "$TEAM" !=  "UF" ]]; do
        echo "That was not one of your choices. Please choose FSU or UF"
        read -r TEAM
done
if [[ "$TEAM" == "FSU" ]]; then
        echo "You chose the better team"
else [[ "$TEAM" == "UF" ]];
        echo "You did NOT choose the better team"
fi

Changes:

Look at Done location, You need to exit the while loop after the user input validation pass.

You need to ask for user's input after he fails with required input. hence the read -r TEAM in while loop.

Your logical comparison was OR instead of AND in the while loop.

Farhad Farahi
  • 35,528
  • 7
  • 73
  • 70
  • Ok. That work. Thanks. I had been told by someone else on a different site that you would embed the if/then/else statement inside the while loop. I was trying that but it would not work. So, I wrote my script a little different from yours and it still works. I did not double bracket the if/then/else statement. – t3kg33k Dec 02 '16 at 14:43
  • You can do that, depends on your situtation, If you want the `if else` gets validated on each `while loop`, you put that inside your `loop block`, but thats not what we want right now. – Farhad Farahi Dec 02 '16 at 14:46