To multiply two numbers directly, you would do something like:
echo 2.77 * 2.0 | bc
It will produce a result to 2 places - the largest number of places of the factors. To get it to a larger number of places, like 5, would require:
echo "scale = 5; 2.77 * 2.0" | bc
This becomes more important if you're multiplying numerals that each have a large number of decimal places.
As stated in other replies, bc is not a part of bash, but is a command run by bash. So, you're actually sending input directly to the command - which is why you need echo. If you put it in a file (named, say, "a") then you'd run "bc < a". Or, you can put the input directly in the shell script and have a command run the designated segment as its input; like this:
cat <<EOF
Input
EOF
... with qualifiers (e.g. you need to write "" as "\", for instance).
Control flow constructs may be more problematic to run in BC off the command line. I tried the following
echo "scale = 6; a = 2.77; b = 2.0; define f(cc) { auto c, d; c = cc; d = a*b*c; return d; } f(0); f(0.001); f(0.02)" | bc
and got a syntax error (I have a version of GNU-BC installed). On the other hand, it will run fine with C-BC
echo "scale = 6; a = 2.77; b = 2.0; define f(cc) { auto c, d; c = cc; d = a * b * c; return d; } f(0); f(0.001); f(0.02)" | cbc
and give you the expected result - matching the example you cited ... listing numbers to 6 places.
C-BC is here (it's operationally a large superset of GNU-BC and UNIX BC, but not 100% POSIX compliant):
https://github.com/RockBrentwood/CBC
The syntax is closer to C, so you could also write it as
echo "scale = 6, a = 2.77, b = 2.0; define f(cc) { return a * b * cc; } f(0); f(0.001); f(0.02)" | cbc
to get the same result. So, as another example, this
echo "scale = 100; for (x = 0, y = 1; x < 50; y *= ++x); y" | cbc
will give you 50 factorial. However, comma-expressions, like (x = 0, y = 1) are not mandated for bc by POSIX, so it will not run in other bc dialects, like GNU BC.
| bc
you are running a newbc
process. It doesn't know anything about the previousbc
processes. – Foreandaftera=2.77 | bc
is also meaningless (I'm surprised it isn't a syntax error actually) sincea=2.77
is an assignment that creates no output forbc
to read and operate on. You would needecho
there like you have on theecho "$d" | bc
line. – Foreandaftera=2.77|bc
starts two subshells, attaching stdout of the first to stdin of the second through a pipe. In the first, it setsa
to 2.77 and terminates, closing stdout. In the second, reading from stdin produces an (almost) immediate EOF, sobc
does nothing. The result is a very expensive no-op; not even the assignment happens in the executing shell environment. But it's certainly not a syntax error: "A 'simple command' is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections" (XCU 2.9.1) – Marianomaribel