a=10.5
b=11.8
c=`expr $a + $b | bc`
echo $c
After execution, it's displaying an error message like non-integer argument
. Why is this not performing arithmetic using expr
?
The error is the same as if you input:
$ expr 10.5 + 11.8
expr: non-integer argument
Expr is complaining that you gave it non-integers. This is because expr
program was not designed for non-integer calculations:
Operands are either integers or strings.
expr
was generated as standard error, your terminal just displays it|
, pipe only transfers standard out, not standard errorBecause bc
did not receive anything to work with, it didn't give you any output at all, as you can see when you try sending nothing (except new-line) to bc
:
$ echo | bc
The result is bc
says nothing. So what you see on your screen with your original command, was still just expr
's complaint via standard error.
For decimal calculations, you can use just bc
and some means to get input to bc
, such as with here-strings:
$ bc <<< '10.5 + 11.8'
22.3
Or, to use variables:
$ a=10.5
$ b=11.8
$ c=$(bc <<< "$a + $b")
$ echo $c
22.3
$(
and )
is a command substitution<<< string
is a here-string syntax, sends the string contents to stdin, which bc receivesinfo coreutils 'expr invocation'
says:
16.4 `expr': Evaluate expressions
=================================
`expr' evaluates an expression and writes the result on standard
output. Each token of the expression must be a separate argument.
Operands are either integers or strings. Integers consist of one or
more decimal digits, with an optional leading `-'. `expr' converts
anything appearing in an operand position to an integer or a string
depending on the operation being applied to it.
However, you can use bc
:
$ a=10.5 b=11.8 c=$(echo "scale=1;$a + $b" | bc -q );echo $c
22.3
{}
button.