Tuesday, April 30, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  28] [ 0]  / answers: 1 / hits: 66494  / 1 Year ago, sat, april 8, 2023, 4:30:12

I'm writing a script and I would like to pass the results from bc into a variable. I've declared 2 variables (var1 and var2) and have given them values. In my script I want to pass the results from bc into another variable say var3 so that I can work with var3 for other calculations. So far I have been able write the result to a file which is not what I'm looking for and also I've been able to echo the result in the terminal but I just want to pass the result to a variable at moment so that I can work with that variable.



echo "scale=2;$var1/var2" | bc

More From » bash

 Answers
2

If you're using bash, you'd better use an here string instead of a pipe as in:



bc <<< "scale=2;$var1/$var2"


This will save you a subshell.



Then, to store the output of a command, use a command substitution:



answer=$(bc <<< "scale=2;$var1/$var2")


Edit.



If you want something even cooler than bc, here's dc (reverse polish calculator):



answer=$(dc <<< "2k $var1 $var2/p")

[#33655] Monday, April 10, 2023, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
eaderitable

Total Points: 368
Total Questions: 117
Total Answers: 111

Location: Tuvalu
Member since Sat, Feb 11, 2023
1 Year ago
;