0

I have this script that runs perfectly well, I would however like to re-run the script if the wrong input is entered, how could this be done?

#! /bin/bash
#! userInput - a script that reads in text and outputs it immediately

echo "Would you like to input some text? Y/N"
        read request
if [[ $request = Y ]]; then
        echo "Please input some text"
                read input
        echo $input
elif [[ $request = N ]]; then
        echo "Thank You"
else
        echo "Invalid Input - Please Input Y for yes or N for no"
fi
  • Please put $request in double quotes (even nices with curly braces like @Andy). When the request has a space, the if-statement will be invalid syntax (and you do not want * replaced by a list of files). About the same is valid for $input (better "${input}"). – Walter A Nov 30 '15 at 20:35
1

This is what select is for.

PS3="Would you like to input some text? <Y/N>   ]"
select choice in "Y" "N"; do
   case $choice in
      "Y")
          echo -n "Please input some text >"
          read input
          echo "$input"
          break
          ;;
      "N")
          echo "Very well."
          break
          ;;
      *)
          echo "Invalid response."
          ;;
    esac
done
| improve this answer | |
0

I would suggest you organize the flow of control to model the problem you're trying to solve. You want to look while the user doesn't want to quit, not forever:

#!/bin/bash

echo -n "Would you like to input some text (Y/N): "
read request

while [[ "${request}" != "N" ]]; do
    if [[ "${request}" == "Y" ]]; then
        echo -n "Please input some text: "
        read input

        echo "You entered '${input}'"
    else
        echo "Invalid input: '${request}'"
    fi

    echo -n "Would you like to input some text (Y/N): "
    read request
done

echo "Thank you"
| improve this answer | |
  • I agree with @DopeGhoti that select would be nice in this case. – Andy Dalton Nov 30 '15 at 20:14
0

How about

#!/bin/bash
# userInput - a script that reads in text and outputs it immediately

while true; do
    echo "Would you like to input some text? Y/N"
    read request

    if [[ $request = Y ]]; then
        echo "Please input some text"
        read input
        echo $input
        break
    elif [[ $request = N ]]; then
        echo "Thank You"
        break
    else
        echo "Invalid Input - Please Input Y for yes or N for no"
    fi
done
| improve this answer | |
  • Thanks I though it would be that I just kept missing the done at the end – S.Jones Nov 30 '15 at 19:50
0

Otherwise if you literally wanted to rerun the script:

else
 exec $0
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.