top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

Shell Arithmetic in Linux?

+1 vote
81 views

List of Arithmetic Operators

+   Addition    
-   Subtraction
/   Division    
*   Multiplication  
 %  Modulus 
++  post-increment 
--  post-decrement 
**  Exponentiation

Using Operators

expr command
In Linux arthmatic operation can be done by the expr command, expr became popular in the days of the Bourne Shell, which did not support math. With Bash and Korn shell, it is generally not needed. expr treats the variable as a string

Example usage

$ z=10
$ z=`expr $z+1`   ---- Need spaces around + sign.
$ echo $z
10+1
$ z=`expr $z + 1`
$ echo $z
11

let command
In Bash and Korn shell we have a command called let which is used for mathematical operations. It is also a little picky about spaces and behave opposite of expr. let also relaxes the normal rule of needing a $ in front of variables to be read.
Example

$ let z=10
$ echo $z
10
$ let z=$z+1
$ echo $z
11
$ let z=$z + 1     # --- Spaces around + sign are bad with let   
$ let z=z+1        # --- no $ to read a variable.
$ echo $z
12

Alternate Method
An alternate method is use of double parenthesis and similar to let command but more forgiving about spaces.

$ ((e=10))
$ echo $e
10
$ (( e = e + 3 ))
$ echo $e
13
$ (( e=e+4 ))  # -- spaces or no spaces, it doesn't matter
$ echo $e
17
posted Aug 18, 2014 by Salil Agrawal

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...