Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 419
Christopher Karsten Avatar asked Nov 10 '16 10:11

Christopher Karsten


People also ask

How do I print a variable in printf?

The following line shows how to output the value of a variable using printf. printf("%d", b); The %d is a placeholder that will be replaced by the value of the variable b when the printf statement is executed. Often, you will want to embed the value within some other words.

Can we assign printf to a variable?

Using printf function, we can print the value of a variable. In order to print the variable value, we must instruct the printf function the following details, 1. specify the format of variable.

Can we use printf in shell script?

printf is a shell builtin in Bash and in other popular shells like Zsh and Ksh. There is also a standalone /usr/bin/printf binary, but the shell built-in version takes precedence. We will cover the Bash builtin version of printf . The -v option tells printf not to print the output but to assign it to the variable.

How do you print a variable in Linux?

Using the printenv Command The printenv command-line utility displays the values of environment variables in the current shell. We can specify one or more variable names on the command line to print only those specific variables.


1 Answers

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
like image 154
Toby Speight Avatar answered Oct 23 '22 09:10

Toby Speight