Linux and Networking

Linux and Networking

4.11. The expr command

The expr command can be used to perform arithmetic operations in shell script. Let’s look at an example of things that can be done with this command:

As you can see in the examples, the arguments of expr are evaluated as expressions and written to the standard output, which is the screen. With expr we can perform simple arithmetic operations.

 

Remember:

The arguments or parameters of expr have to be separated by blanks for expr to understand them.

 

If, for example, we do RESULT=`expr $a + 1`, keep in mind not to leave any blank space in the assignment (=).

The arguments of the expr command are taken as expressions and must be separated by blanks. The expr command evaluates its arguments and writes the result to standard output. The most common use of the expr command is to perform simple arithmetic operations.

 

To multiply and divide we will do it as follows:

 

$ expr 2 \* 2

4

$ expr 2 / 2

1

 

And if we want to do more complicated things we will have to resort to the bc command, as we have said:

 

$ echo «scale=2; 10 / 3″|bc -l

3.33

 

In this case divide 10 by 3 and get the result of the division with two decimal places.

 

Suggested exercise.

Create a script that does the basic operations of a calculator (addition, subtraction, multiplication and division).

The Demeter Project