J.Zil
J.Zil

Reputation: 2449

Asking for user input in bash to set variable

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?

Upvotes: 2

Views: 3572

Answers (2)

Maximiliano Padulo
Maximiliano Padulo

Reputation: 1522

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.

Upvotes: 3

anubhava
anubhava

Reputation: 785156

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

Upvotes: 2

Related Questions