slm's answer here hasn't taken into account that you asked about the Korn shell, not about the Bourne Again shell. The (93) Korn shell has no built-in expr
command, so when using expr
in Korn shell scripts you are using an external expr
command. This is not a problem per se. After all, it's how one did things with the Bourne shell, which also had no expr
built-in command. But as M. Kohen points out, one might prefer to use shell built-ins when a shell has them. And the Korn shell has.
M. Kohen points to the arithmetic substitution available in the Korn shell. It's important to remember that this is a substitution, so you must do something with the substituted result if you don't want to just run it as a command. The more complete form of M. Kohen's answer (fixing the operator precedence error along the way) is thus:
AVERAGE="$(( (first + second + third) / 3))"
But there are two other ways of doing this in the Korn shell. The Korn shell has a built-in command named let
that does arithmetic evaluation on each of its arguments:
let "AVERAGE = (first + second + third) / 3"
Every argument to the command is a single expression, so whitespace needs to be quoted as here.
It also has a piece of syntax that is described in one ksh clone's manual as "syntactic sugar for let
" with the expression turned into a single argument to that command:
(( AVERAGE = (first + second + third) / 3 ))
Further reading
expr
to do the sums, but didn't realize you also needed it for the division? – Barmar Oct 02 '14 at 14:37