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
|the command on the right of the pipe is executed in a subshell, and it takes resources to open a new subshell (it's like opening a new instance of bash to execute that command). If you can avoid it, avoid it. Here, piping anechotobcwill run the commandbcin a subshell and is, in some sense, retarded (no offence), since bash has the wonderful here-string construct<<<to avoid stupid things like these. – gniourf_gniourf Dec 15 '12 at 22:19/bin/sh(dash) instead of bash, but dash doesn't have<<<. – Gilles 'SO- stop being evil' Dec 15 '12 at 22:33bcif it's in a subshell like in your answer? – gniourf_gniourf Dec 15 '12 at 22:45<<<in bash is a waste of resources (but not an important one). – Gilles 'SO- stop being evil' Dec 21 '12 at 01:42bcwithvar3=$(echo … | bc). It's in$?, same as withvar3=$(bc <<<…). – Gilles 'SO- stop being evil' Dec 21 '12 at 01:43<<<is slow: it creates a temporary file, which is slower than a pipe. The data has to come from somewhere after all. – Gilles 'SO- stop being evil' Dec 21 '12 at 02:37time for i in {1..10000}; do : <<< ""; donewithtime for i in {1..10000}; do echo "" | : ; done, you'll see a dramatic difference. Then you're right, a heredoc is slightly faster than a herestring. But it's more awkward to type as a one-liner. – gniourf_gniourf Dec 21 '12 at 07:57/tmpon tmpfs, I don't see any difference betweenecho … |and<<<. With ksh,<<<is indeed measurably faster (and faster than bash). – Gilles 'SO- stop being evil' Dec 21 '12 at 10:17echo | .... I really don't care. – gniourf_gniourf Dec 21 '12 at 12:11<<<, it's not just about slowness! It's also always a problem on read-only environments, because on more complex scripts, your screen will be flooded with ugly error messages. And here's another thing people sometimes have difficulties to understand: this may happen __even underroot! Because evenrootcan't write everywhere, if partitions are mounted read-only. Very common on other companies' systems that you only have restricted access to. Likewise, recovery consoles would show that behavior by default as well. – syntaxerror Oct 24 '14 at 00:27