I have a calculation on a Linux shell, something like this
echo "scale 4;3*2.5" |bc
which gives me an result, now I like to pipe the result of this calculation into an Variable so that I could use it later in another command,
piping into files work, but not the piping into variables
echo "scale=4 ; 3*2.5" | bc > test.file
so in pseudo-code i'm looking to do something like this
set MYVAR=echo "scale=4 ; 3*2.5" | bc ; mycommand $MYVAR
Any ideas?
The bc command allows you to specify an input and output base for operations in decimal, octal, or hexadecimal. The default is decimal. The command also has a scaling provision for decimal point notation.
To declare a variable, just type the name you want and set its value using the equals sign ( = ). As you can see, to print the variable's value, you should use the dollar sign ( $ ) before it. Note that there are no spaces between the variable name and the equals sign, or between the equals sign and the value.
A shell variable is created with the following syntax: "variable_name=variable_value". For example, the command "set COMPUTER_NAME=mercury" creates the shell variable named "COMPUTER_NAME" with a value of "mercury". For values with spaces, quotation marks must be used.
$() – the command substitution. ${} – the parameter substitution/variable expansion.
You can do (in csh):
set MYVAR=`echo "scale 4;3*2.5" |bc`
or in bash:
MYVAR=$(echo "scale 4;3*2.5" |bc)
MYVAR=`echo "scale=4 ; 3*2.5" | bc`
Note that bash doesn't like non-integer values - you won't be able to do calculations with 7.5 in bash.
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