How to pass variable within printf How to pass variable within printf shell shell

How to pass variable within printf


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 lrusread -p "Are you sure you want $lrus lrus? " -r ans


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%


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"