How to pass variable within printf

Christopher Karsten picture Christopher Karsten · Nov 10, 2016 · Viewed 17.2k times · Source

I am trying to echo a variable within a printf. I first prompt the user for input using the command below

printf 'Specify lrus [default 128]:         ' ;read -r lrus

Next it prompts the user again to see if he wants the input used from the previous question:

printf 'Are you sure you want $lrus lrus:       ' ;read -r ans

For example the output will look like the below:

Specify lrus [default 128]:     60
Are you sure you want 60 lrus:  yes

The above output is what I am trying to achieve allowing to pass the previous input variable to the next question using printf.

Answer

Toby Speight picture Toby Speight · Nov 10, 2016

Your problem is that you are using single-quotes. Parameters are not expanded within single quotes.

Parameters are expanded in double-quotes, though:

printf "Are you sure you want $lrus lrus: "

Note that there's no need for a separate print; it's better to use the -p argument to read (that understands your terminal width, for one thing):

read -p "Specify lrus [default 128]: " -r lrus
read -p "Are you sure you want $lrus lrus? " -r ans