LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Getting a variable from printf (https://www.linuxquestions.org/questions/linux-newbie-8/getting-a-variable-from-printf-926565/)

mp85 01-30-2012 01:47 PM

Getting a variable from printf
 
I had to do some rounding in a script using printf, but how do I get the output to become a variable

Code:

$velper=141.600
printf "%.0f\n" $velper

What do I add so that i can have a new variable become the result of printf
(I have a feeling this is really simple)


thanks

MTK358 01-30-2012 02:30 PM

Code:

myvar="$(command)"
This will put the output of "command" into variable "myvar".

T3RM1NVT0R 01-30-2012 02:31 PM

@ Reply
 
Hi mp85,

Welcome to LQ!!!

If you are trying to round of the value of variable velper and want to replace the existing value of velper to the rounded of value then you can do it as follows:

Code:

velper=`printf "%.0f\n" $velper`
If you want to save the value to any other variable then you can replace the velper on left hand side with any other variable as follows:

Code:

new=`printf "%.0f\n" $velper`

Dark_Helmet 01-30-2012 02:31 PM

Assuming this is bash:

Code:

newVariable=$(printf "%.0f\n" $velper)
Keep in mind that you may want to remove the '\n' in your format specification for printf. If you do not, then newVariable will have a newline as part of its value--which is probably not what you want.

mp85 01-30-2012 02:41 PM

Quote:

Originally Posted by Dark_Helmet (Post 4588620)
Assuming this is bash:

Code:

newVariable=$(printf "%.0f\n" $velper)
Keep in mind that you may want to remove the '\n' in your format specification for printf. If you do not, then newVariable will have a newline as part of its value--which is probably not what you want.

Thanks so much, I did think I tried this but with the \n which i assume caused it to fail. I had no idea what that part of the printf function was doing.

David the H. 01-31-2012 09:28 AM

Or alternately, still assuming bash:

Code:

$ velper=141.600
$ printf -v newvar "%.0f" "$velper"
$ echo "$newvar"
142

Use "help printf" for a short summary, and "man bash > SHELL BUILTIN COMMANDS" for more detail.

And remember, always quote your variable substitutions. Get into the habit now.


All times are GMT -5. The time now is 10:37 PM.