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 + 242
Perform a subtraction operation as follows:
$ expr 42 - 240
Perform a division operation as follows:
$ expr 40 / 104
Perform a modulus (getting remainder) operation as follows:
$ expr 42 % 102$ expr 4 * 10expr: syntax error
With the expr
command, we cannot use *
for multiplication. We need to use *
for multiplication:
$ expr "4 * 10"4 * 10$ expr 4 * 1040
We will write a simple script to add two numbers. Write the shell script, arithmetic_01.sh
as follows:
!/bin/bash x=5 y=2 z=`expr $x + $y` echo $z
Test the script as follows:
$ chmod +x arithmetic_01.sh
$ ./arithmetic_01.sh
This is the output:
7
Let's write a script to perform all the basic arithmetic operations. Write the Shell script called arithmetic_02.sh
as follows:
#!/bin/bash ...