Vijay Vijay - 1 year ago 221
Bash Question

shell scripting arithmetic operations

in general i will use expr inside shell scripts for doing arithmetic operations.

is there a way where we can come up with arithmetic operation in a shell script without using expr?

Answer Source

Did you tried to read "man ksh" if you're using ksh?

"man bash", for example, has enough information on doing arithmetics with bash.

the command typeset -i can be used to specify that a variable must be treated as an integer, for example typeset -i MYVAR specifies that the variable MYVAR is an integer rather than a string. Following the typeset command, attempts to assign a non integer value to the variable will fail:

   $ typeset -i MYVAR
   $ MYVAR=56
   $ echo $MYVAR
   $ MYVAR=fred
   ksh: fred: bad number

To carry out arithmetic operations on variables or within a shell script, use the let command. let evaluates its arguments as simple arithmetic expressions. For example:

   $ let ans=$MYVAR+45
   echo $ans

The expression above could also be written as follows:

   $ echo $(($MYVAR+45))

Anything enclosed within $(( and )) is interpreted by the Korn shell as being an arithmetic expression

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download