Arithmetic in Shell Scripts



next up previous contents index
Next: Interactive Shell Tips Up: Shell Programs (Scripts) Previous: Unix Commands inside

Arithmetic in Shell Scripts

The Borne shell does not have any built-in ability to evaluate simple arithmetic statements. This is all right because the Unix command expr performs simple mathematics as well as numerical comparisons from the command line:

% expr 3 + 2   	Add 3 and 2.   
5   	The shell's answer.   

These numerical comparisons are only for integers, with mandatory spaces separating the integers and operators. Operators that are special shell characters, like * or |, must be preceded with an backslash \ or surrounded by quotes. The permitted operations are:


expr OPERATIONS
x + y
Add two numbers.
x - y
Subtraction.
x * y
Multiplication.
x / y
Division.
x % y
Remainder.
x < y
Returns 1 if true 0, if false.
x <= y
Less than or equal to.
x = y
Test for equal to.
x != y
Test for not equal to.
x >= y
Greater than or equal to.
x > y
Greater than.
x | y
x if , else y.
x & y
x if both x and y , else 0.
x : y
String compare. See manual.

From within a shell script you use expr to increment a variable by assigning the output of expr to the variable:


N=`expr $N + 1` Increment N by one.

We use this idea in the example below in which we run the user program bigmat with input files given on the command line and with the output stored in a different file for each input file name. The output file names are output.N where N is used as a counter:


#!/bin/sh N="1" Be sure to initialize N. for file Loop over the arguments. do outfile="output.$N" Create output file name. echo "Running bigmat - input: $file output: $outfile." bigmat < $file > $outfile N=`expr $N + 1` Increment N. done exit



next up previous contents index
Next: Interactive Shell Tips Up: Shell Programs (Scripts) Previous: Unix Commands inside