Reputation: 1035
I am working with shell scripting on Linux.
I have 2 double variables and i want to divide them, and put the results into another variable.
I tried the following (does not work) :
#!/bin/bash
A=333.33
B=111.11
C="$A / $B" | bc -l
although the following does work:
#!/bin/bash
A=333.33
B=111.11
echo "$A / $B" | bc -l
what am i doing wrong?
Thanks Matt
Upvotes: 0
Views: 3094
Reputation: 3838
When you use a pipe, you must to push an output :
commandA|commandB
The commandA
output is pushed in the pipeline and processed by commandB
. So commandA
must print an output in the stdout
stream which is processed by the pipe.
So you could use instead :
C=$(echo "$A / $B"|bc -l)
# or
C=`echo "$A / $B"|bc -l`
# or
C=$(bc -l <<< "$A / $B")
# or
C=`bc -l <<< "$A / $B"`
If you want to set the result into a variable.
Upvotes: 0
Reputation: 597
That's the working version:
#!/bin/bash
A=333.33
B=111.11
C=`bc -l <<< "$A/$B"`
echo $C
Upvotes: 0
Reputation: 97968
Pipes work on output streams, and:
C="$A / $B" | bc -l
does not send "$A / $B"
to the output stream, instead just sends an eof.
You can do this:
C=$(echo "$A / $B" | bc -l)
to get the result into C
.
Upvotes: 2
Reputation: 7171
"$A / $B" is just a string so piping (|) it to "bc -l" doesn't work. A pipe "connects" stdout from one process with stdin on another. echo "$A / $B" on the other hand passes the value of the string to stdout and the pipe passes it to stdin of bc, which works as expected.
Upvotes: 0