0

After "Enter server name" and setting the $servselect variable in the script below the variable is lost after the "Hello" and "Goodbye" options are selected. This requires completing "Enter server name" prompt again. Is there a way to maintain that variable until the script completely exits? Any advice would be greatly appreciated.

#!/bin/bash
#
while true; do
    read -p "Enter server name: " servselect
    servselect=${servselect:-servselect}
    echo $servselect has been selected!

    printf '%s\n' \
        "" \
        "[A] Hello" \
        "[B] Goodbye" \
        "[Q] Quit" \
        ""
        read -n1 -p 'Enter response here:' response
        case $response in
            [Aa]* )
                printf '%s\n' \
                    "" \
                    "Hello, $servselect" \
                    ""
                    ;;
            [Bb]* )
                printf '%s\n' \
                    "" \
                    "Goodbye, $servselect" \
                    ""
                    ;;
            [Qq]* )
                printf '%s\n' \
                    "" \
                    "Quitting..." \
                    ""
                    break
                    ;;
            * )
                printf '%s\n' \
                    "" \
                    "Please choose A, B, or Q" \
                    ""
                    ;;
        esac
done
3

You are setting it inside the loop, so it will keep prompting you for it.

I would have two loops - one to prompt for the server name and keep prompting until a valid value is provided, and then one to do option A or B or Quit.

For pure programming questions like this, you may be better off asking on stackexchange

  • Hey ivanivan, thanks for the response. Do you have an example of how this would function as two separate loops? I can't seem to find an example. – hashwagon Jul 4 '17 at 7:18
  • 2
    @hashwagon Something like while true; do read -p "Enter server name: " servselect; is_valid $servselect && break; echo invalid server name: $servselect; done for the first loop, and then the same loop as in your question, but without prompting for servselect. But in your posted code there is no notion of valid or invalid servselect. So maybe you don't care about such validation, and don't need two loops. In that case, simply move the prompting out of the loop, that's all. – janos Jul 4 '17 at 11:19
  • @janos Thank you so much. This worked after adding = after is_valid, e.g., is_valid=$servselect. – hashwagon Jul 5 '17 at 15:47

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.