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
1
  • 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, 2015 at 20:35

4 Answers 4

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
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"
1
  • I agree with @DopeGhoti that select would be nice in this case. Nov 30, 2015 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
1
  • Thanks I though it would be that I just kept missing the done at the end
    – S.Jones
    Nov 30, 2015 at 19:50
0

Otherwise if you literally wanted to rerun the script:

else
 exec $0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .