1

How to write a bash script, if enter empty value "", or other value than 1 and 2 will not end the script, and will let user to renter 1 or 2. Basely if user type wrong, will let user to renter.

    echo Press 1 for services and 2 for chkconfig?
    echo -n "Please input yes or no: "
    read ANS
if [ $ANS != "" ];

if [ $ANS == 1 ];
then
   service vsftpd status
elif [ $ANS == 2 ];
then
 service vsftpd status
else
echo please input 1 oe 2

fi
~

2 Answers 2

1

Try this:

while true
do
    echo -n "Enter 1 for status, 2 for chkconfig, or q to quit: "
    read ANS
    if [ "$ANS" = q ]
    then
       break
    elif [ "$ANS" = 1 ]
    then
       service vsftpd status
       break
    elif [ "$ANS" = 2 ]
    then
       service vsftpd chkconfig
       break
    else
       echo "Invalid input.  Try again."
    fi
done

Notes:

  • To allow the use to reenter an answer if he failed to enter a proper answer the first time, the code is placed in a while loop. When a satisfactory answer is given, the break command is used to exit the loop. Lacking a satisfactory answer, the loop repeats until one is entered.

  • I added a "quit" option as this is something that users will generally insist on.

  • Inside [ style tests, the symbol for equality is =. Some shells will accept == here but others will choke on it. On the other hand, if [[ style tests are used (requires bash), then == is the correct symbol for equality.

  • In [ style tests, it is important to put shell variables in double-quotes. Thus, replace [ $ANS = 1 ] with [ "$ANS" = 1 ]. Otherwise, if the user type nothing but enter, then ANS would be empty and script would fail with an error. With [[ style tests, the quotes are not needed.

Sign up to request clarification or add additional context in comments.

Comments

1

This will keep asking until you enter a "1" or a "2".

#!/bin/sh
while [ 1 ]; 
do
echo Please enter 1 or 2:
read ANS;
    if [ "$ANS" = "1" ]; then echo You entered 1!; break; fi
    if [ "$ANS" = "2" ]; then echo You entered 2!; break; fi
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.