1

Im currently stuck trying to solve a small problem where I want to pass a variable to the basic calculator program and safe the outcome of the calculation. so my idea is to pipe input in form of echo into bc and assign the outcome of the calculation to a variable to echo it afterwards as demonstrated on console:

enter image description here

I came up with the following code:

#!/bin/bash
# sqrt test
a=20736
echo "a is $a" # will print a is 20736
b=sqrt"($a)"|bc
echo "b is $b" # will print b is 
echo sqrt"($a)"|bc # will print 144

I don't understand why the output from echo "b is $b" will be "b is" without actually printing the calculated value. What am i missing?

Snackaholic
  • 590
  • 7
  • 27

1 Answers1

2

You need to enclose the bc command in a bash command substitution expression $():

#!/bin/bash
# sqrt test
a=20736
echo "a is $a" # will print a is 20736
b=$(echo sqrt"($a)"|bc)
echo "b is $b" # will print b is 144
echo sqrt"($a)"|bc # will print 144

So the output is:

a is 20736
b is 144
144

As @kvantour mentioned in a comment, if you test your bash scripts using shellcheck.net, the situation I've mentioned above is clearly identified:

Line 5:
b=sqrt"($a)"|bc
^-- SC2036: If you wanted to assign the output of the pipeline, use a=$(b | c) .
^-- SC2030: Modification of b is local (to subshell caused by pipeline).
 
Line 6:
echo "b is $b" # will print b is
           ^-- SC2031: b was modified in a subshell. That change might be lost.
Alexandre Juma
  • 3,128
  • 1
  • 20
  • 46