I'm pretty new at shell scripts, but I would like to write a basic script where the bash file will echo a different line of text depending on the user input. For example if the script asks the user "Are you there?" and the user input is "yes" or "Yes" then the script would echo something like "hello!". But if the user input is "no" or "No" the script would echo something else. And finally, if the user input is something other than yes/Yes or no/No, the script would echo "Please answer yes or no". Here is what I have so far:
echo "Are you there?"
read $input
if [ $input == $yes ]; then
echo "Hello!"
elif [ $input == $no ]]; then
echo "Are you sure?"
else
echo "Please answer yes or no."
fi
However, no matter the input, I always get the first response ("Hello!")
Also, I would like to incorporate text to speech (as I have done with other bash file projects using festival). In other bash files I have done it this way:
echo "Hello!"
echo "Hello!" | festival --tts
Is there a way to incorporate this into the if then/yes no prompt above? Thank you in advance, I'm using this to make simple bash files and to help myself learn.
Best Answer
The main problem is here:
In bash, usually,
$foo
is the value of the variablefoo
. Here, you don't want the value, but the name of the variable, so it should be just:Similarly, in the
if
tests,$yes
and$no
should be justyes
andno
, since you just want the stringsyes
andno
there.You could use a
case
statement here, which (IMHO) makes it easier to do multiple cases based on input:You could wrap the two
echo
statements and the use offestival
in a function to avoid repeating yourself:With
$input
, bash replaces this with its value, which is nothing initially, so theread
command run is:And
read
by default stores the input in the variableREPLY
. So you can, if you want, eliminate theinput
variable altogether and use$REPLY
instead of$input
.Also have a look at the
select
statement in Bash.