I'm working on a script for class as a final project. We have to ask for values (city, state, zip) five times, but the state can only be MI, IN, IL, or OH. I'm trying to do this with a while loop inside of a while loop, but I have no idea how to do it properly.
Here's what I have so far:
COUNT=0
while [ "$COUNT" -lt "5" ]; do
clear
echo "Enter City: "; read CITY
echo "Enter State: "; read STATE
while [[ "$STATE" != "MI" && "$STATE" != "IN" && "$STATE" != "IL" && "$STATE" != "OH" ]]; do
echo "Sorry, that's not an accepted state."; read STATE
done
echo "Enter Zip: "; read ZIP
COUNT="$COUNT"+1
done
sleep 5
I have a feeling I'm way off... and I have no idea how to fix it.
My syntax for the while loop that checked STATE was bad. In bash, you have to use -a instead of &&:
while [ "$STATE" != "MI" -a "$STATE" != "OH" -a "$STATE" != "IL" -a "$STATE" != "IN" ];do
echo "Sorry, that's not an accepted state."
echo "Enter State: "; read STATE
done
And for some reason, my bash won't recognize the let command... so I have to use expr instead for a counter:
COUNT=0
while [ "$COUNT" -le "5" ]; do
echo "Count is less than 5."
COUNT=`expr $COUNT + 1`
done
Actually, using && within double square brackets is correct. The single open square bracket (actually the test command) does not support double ampers and as you have noticed it does need -a. This is a test command syntax requirement, not bash; most people don't realise that the [ is a command and not a shell built-in.
Using test (or [) is less efficient than using the shell (bash or Kshell) built-in [[. There are times where using test makes sense, but for most scripts I believe that the built-in is best.
I just had a look at your original script and didn't notice that you were issuing the read before your echo "try again." Other than that, it works for me.