Using the expr command for arithmetic

We can use the expr command for arithmetic operations. The expr command is an external command; the binary of the expr command is stored in the folder called /usr/bin/expr.

Perform an addition operation as follows:

    $ expr 40 + 2
    42  

Perform a subtraction operation as follows:

    $ expr 42 - 2
    40
  

Perform a division operation as follows:

    $ expr 40 / 10
    4  

Perform a modulus (getting remainder) operation as follows:

    $ expr 42 % 10
    2
    $ expr 4 * 10
    expr: syntax error  

With the expr command, we cannot use * for multiplication. We need to use * for multiplication:

    $ expr "4 * 10"
    4 * 10
    $ expr 4 * 10
    40  

We will write a simple script to add two numbers. Write the shell script, arithmetic_01.sh as follows: ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.