12

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.

Christopher Karsten
  • 387
  • 1
  • 2
  • 12

4 Answers4

21

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
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
9

When using printf, use format specifiers. Put a %s where you want your value to go, and then put the value in the next parameter:

printf 'Are you sure you want %s lrus:       '  "$lrus"
read -r ans

This is safer and more robust than using double quotes to inject the variable into the printf format string. If you use double quotes, you will be unable to write out variables containing e.g. 100%:

$ var='100%'; printf "Value is $var"
bash: printf: `%': missing format character

$ var='100%'; printf "Value is %s" "$var"
Value is 100%
that other guy
  • 116,971
  • 11
  • 170
  • 194
1

According to the SC2059 :

Don't use variables in the printf format string. Use printf "..%s.." "$foo".

You can use:

printf "Are you sure you want %s lrus: " "$lrus"
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
0

you can try this;

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

or

printf "Are you sure you want ${lrus} lrus:       " ;read -r ans
Mustafa DOGRU
  • 3,994
  • 1
  • 16
  • 24