Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pipe bc-calculation into shell variable

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?

like image 646
Seb Avatar asked Apr 15 '11 08:04

Seb


People also ask

What is the use of base value calculator BC in shell script?

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.

How do you declare a value to a variable in shell script?

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.

How do you create a shell variable?

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.

What does ${} mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.


2 Answers

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)
like image 72
bmk Avatar answered Sep 21 '22 22:09

bmk


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.

like image 21
Erik Avatar answered Sep 17 '22 22:09

Erik