linuxshellunixaix

How to pass variable within printf


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.


Solution

  • 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: "
    

    If you're using a shell that supports read -p, then avoid the separate print. Supplying a prompt this way is better (it 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