Looping through for user input

Legends,

I want to remain in the script until user passes the correct name.
I had tried the below code; but it didn't work out.
Please help

echo "\nPlease enter the source system: \c"
while read SYSTEM_NAME
do
if [[ $SYSTEM_NAME == "L1" || $SYSTEM_NAME == "L2" || $SYSTEM_NAME == "P1" || $SYSTEM_NAME == "P2 ]];
then
echo "\nMaking $SYSTEM_NAME as source system for particular script"
else
echo "\nPlease enter the source system as L1 L2 P1 P2"
echo "\nPlease enter the product name FUNDDB/SMF: \c"
fi
done

But, this is not working.

Please let us know the expected output and the error which u got??

In your code, you'd have to break out of the loop when the test passes. Or, do the test directly in while, then read at the end of loop:

#!/bin/bash

echo "Please enter the source system: "
read SYSTEM_NAME

while ! [[ $SYSTEM_NAME == "L1" || $SYSTEM_NAME == "L2" || $SYSTEM_NAME == "P1" || $SYSTEM_NAME == "P2" ]] ; do
      echo "\nPlease enter the source system as L1 L2 P1 P2"
      read SYSTEM_NAME
done

echo "Making $SYSTEM_NAME as source system for particular script"

#continue with  $SYSTEM_NAME

When you are coming out of loop? seems , it's in infite. exit from while once you get the usernames you wanted.

Regards
Ravi

Easier to read with a case statement. Note the use of "break" to get out of "while read". Not sure where the "Please enter product" line should go.

echo "\nPlease enter the source system: \c"
while read SYSTEM_NAME
do
   case "${SYSTEM_NAME}" in
      "L1"|"L2"|"P1"|"P2")
         echo "\nMaking $SYSTEM_NAME as source system for particular script"
        break
        ;;
   esac
   echo "\nPlease enter the source system as L1 L2 P1 P2"
done

echo "\nPlease enter the product name FUNDDB/SMF: \c"
1 Like

Mirni.
the code is on the lines 30-35 ,and while running it throws error on different piece of code.

./switch_dist.sh: syntax error at line 41: `(' unexpected

And, at 41st line, i have following statement in place. Looks like while is not working with parenthesis.

41 echo "\nDo you wish to continue...(y/n): \c"

---------- Post updated at 05:04 AM ---------- Previous update was at 04:56 AM ----------

Thanks methyl, case statement worked :slight_smile: