Home > other >  Why does 'read -p' only remember one variable?
Why does 'read -p' only remember one variable?

Time:08-24

I figured out through a tutorial that using read -p would allow me to take the response as a variable. So I did this madlibs kind of thing to test it, hoping that I could repeatedly have user input translated to a variable, then back into output.

Here's an exerpt:

read -p "What is your favorite fruit?" fruit
echo Oh, I see...
sleep 2s

read -p "And what is your mama's name?" mama
echo Amazing...
sleep2s

read -p "And how many years have you been a little bitch?" years
echo Understood...
sleep 2s

echo So let me get this straight...
echo Your favorite fruit is $fruit
echo Your mama's name is $mama
echo And you have been a little bitch for $years years.

Now let's say I answered Apples, Martha, 3. When I do this, my output comes out:

So let me get this straight...
Your favorite fruit is Apples.
Your mama's name is $mama
And you have been a little bitch for $years

Only the first variable is being output properly, the rest isn't. I have tried using different notations for the variables mama and years, changing them for mumuh and yuurs, but no alas.

Is there something obvious I am missing? Am I misunderstanding how the read command handles the created variables?

CodePudding user response:

This has nothing to do with read. your script is simply missing some quotes for the string sequences.

so your output lines should more look like this:

echo "So let me get this straight..."
echo "Your favorite fruit is" $fruit
echo "Your mama's name is" $mama
echo "And you have been a little bitch for" $years "years."

you could even wrap the variables in the string like this:

echo "And you have been a little bitch for ${years} years."

for a bit more details, you might want to read this question.

CodePudding user response:

The problem lies in this single line:

echo Your mama's name is $mama

because the shell finds an apostrophe (single quote) which must be matched (closed) by another, but there is none.

So, as the previous reply says, it is a problem of quoting, but only this line needs it because of the literal single quote which must be echoed literally and not interpreted.

A mean shell should complain that there is an unmatched quote; my bash says:

Your favorite fruit is Apple

-bash: test.sh: line 15: unexpected EOF while looking for matching `''

Modify that line so it reads:

echo "Your mama's name is " $mama

and you are set.

If it happens that a matching closing single quote is found, the text between the apostrophes is not expanded (no variable substitution), and it seems this happened to you: in fact, the output still contained the "$". Didn't you see an error message? Strange.

  • Related