pina
November 7, 2013, 7:11am
1
I'm converting decimal to integer with bc, and I'd like to assign the integer output from bc to a variable 'val'.
E.g. In the code below: If b is 5000.000, lines 6 and 8 will output:
5000
(5000.000+0.5)/1 | bc
I'd like val to take the value 5000 though, rather than 5000.000
Does someone have any idea how to do that?
#! /bin/bash
while read b
do
echo "($b+0.5)/1" | bc # line 6 - works
val= "($b+0.5)/1 | bc" # line 7 - doesn't work
echo $val # line 8
done < infile
pina:
I'm converting decimal to integer with bc, and I'd like to assign the integer output from bc to a variable 'val'.
E.g. In the code below: If b is 5000.000, lines 6 and 8 will output:
5000
(5000.000+0.5)/1 | bc
I'd like val to take the value 5000 though, rather than 5000.000
Does someone have any idea how to do that?
Try:
#! /bin/bash
while read b
do
echo "($b+0.5)/1" | bc # line 6 - works
val=$(($b+0.5)/1 | bc) # line 7 - should now work
echo $val # line 8
done < infile
Basically $(...) invokes command substitution such that the output of command/subshell can be assigned to a variable.
Andrew
apmcd47:
Try:
#! /bin/bash
while read b
do
echo "($b+0.5)/1" | bc # line 6 - works
val=$(($b+0.5)/1 | bc) # line 7 - should now work
echo $val # line 8
done < infile
Basically $(...) invokes command substitution such that the output of command/subshell can be assigned to a variable.
Andrew
@ apmcd47 your solution gives error
if ksh93
then this will work
val=$((b+0.5/1))
Try this for bash
$ b=5000
$ echo "($b+0.5)/1" | bc
5000
$
$ variable=$(echo "($b+0.5)/1" | bc )
$ echo $variable
5000
if floating point is needed then try
$ var=$(echo "scale=1;$b+0.5/1" | bc)
$ echo $var
5000.5
pina
November 7, 2013, 7:36am
4
Thanks, Akshay Hedge and Andrew!
This works nicely:
variable=$(echo "($b+0.5)/1" | bc )
The command substitution didn't for some reason.