Monday, July 26, 2010

5 different ways of doing Arithmetic operations in UNIX



 In this article, we will see the different  options available in performing arithmetic operations in UNIX . These will come handy while working at the command prompt or for writing scripts. For the sake of simplicity,we will take the example of adding two numbers.

1. The first example makes use of the expr command. All the other arithmetic operators(-,/,%) can be used in the same way except for *(multiplication).
$ x=3
$ y=4
$ expr $x + $y
7
  To multiply the numbers, precede the * with a \. This is done in order to prevent the shell from interpreting the * as a wild card.

$expr $x \* $y
12
2. bc command can also be used for arithmetic operations.
$ echo $x + $y | bc
7
3. The ((..)) notation does provide options for arithmetic operations.
$ echo $(($x+$y))
7
4. The let command can also be used for arithmetic operations. Notice here the $ symbol is not used against the variable.
$ let z=x+y
$ echo $z
7
    let can work with unary  operators as shown below:
$ let z=++z
$ echo $z
8
5. The awk command  used as shown below to do the arithmetic operations of shell variables.
$ echo "" | awk '{print '$x' + '$y'}'
7
Enjoy Arithmetic!!!


Note: The above mentioned methods are applicable for shells ksh, sh and bash, and not in csh or tcsh.

3 comments: