Tuesday, December 25, 2012

Shell Arithmetic using expr


  • shell treats all shell variables as strings.
  • shell uses the expr command  to  perform integer arithmetic.
  • expr command cannot do real or non-integer arithmetic.
  • expr takes two integer arguments and an operand and writes the result to the standard output. If the output need to be stored in a variable, command substitution(`) need to be used.

$ expr 1 + 1
2

$ a=`expr 1 + 1`
$ echo $a
2

There must be spaces between the operand and the arguments.

Note: * is the multiplication operand. But * has special meaning to the shell. Hence while using *, it should be shielded using \ character.

$ expr 2 \* 2
4

No comments:

Post a Comment