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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With