1

When bash scripting, I frequently find myself doing something like this:

bc <<< "64*`cat`"

or

bc <<< "64*`dd`"

if I want to multiply stdin by 64. Is there a better way to substitute stdin into a string (or into a command line, such as in seq 1 2 $(cat))?

e0k
  • 6,961
  • 2
  • 23
  • 30
markasoftware
  • 12,292
  • 8
  • 41
  • 69

2 Answers2

1

There's a slightly more efficient way to do it, assuming your platform represents stdin as (character special) file /dev/stdin (which is quite likely):

$ echo 2 | bc <<< "64 * $(</dev/stdin)"
128

$ echo 5 | seq 1 2 "$(</dev/stdin)"
1
3
5

However, while this avoids a call to an external utility such as cat, it is more verbose.

Community
  • 1
  • 1
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

Another solution without using string expansion:

(echo -n '64*'; cat) | bc

But for a simple multiplication you actually don't need to use bc and you can multiply directly in bash:

read a
echo "$((a*64))"
martin.macko.47
  • 888
  • 5
  • 9