2

I want to have something which asks the user - "Which environment would you like to load?" - with valid response being either "production" or "development". If an answer is given which doesn't match either it re-asks the question. I want it to set the $production variable so I can run different parts of code later on. This is the closest I could do myself:

read -n1 -p "Which environment would you like to load? [production,development]" doit 
case $doit in  
  production) echo $production=1 ;; 
  development) echo $production=0 ;; 
  *) echo ... ;; 
esac

It doesn't seem to set the variable when I run it, so I don't know what I am doing wrong. Furthermore how do I make it to re-ask the question when a valid response isn't given?

2 Answers 2

3

If I understood you correctly, this is what you're looking for:

#!/bin/bash    
while true; do
  read -p "Which environment would you like to load? [production,development]" ANS
  case $ANS in 
    'production') 
       production=1
       break;;
    'development') 
       production=0  
       break;;
    *) 
       echo "Wrong answer, try again";;
  esac
done
echo "Variable value:$production"

You start an infinite loop to ask for user input until it's valid.

If it's not valid it goes to default *) and you inform the user that it's wrong and then ask again, continuing in the loop.

When a match is found, you set your production variable and go out of the loop (with break). Now you code can continue with whatever you need, you got your variable setted up.

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

Comments

2

Problem is your use of read -n1 which will accept only one character in input.

Use:

read -r -p "Which environment would you like to load? [production,development]" doit

To set a default value while reading use -i 'defaultVal'option:

read -r -ei 'production' -p "Which environment would you like to load? [production,development]" doit

1 Comment

I would add that it is wise to always use the -r switch on read as well, because it prevents unexpected behaviour when the user types special characters.

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.