views:

115

answers:

2

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?

A: 

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
   56
   $ 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
   101
   $

The expression above could also be written as follows:

   $ echo $(($MYVAR+45))
   101
   $

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

zed_0xff
i did not find any thing in the man page.
Vijay Sarathi
http://osr507doc.sco.com/en/OSUserG/_math_on_var_in_ksh.htmlhttp://www.bo.infn.it/alice/alice-doc/mll-doc/impgde/node18.html
zed_0xff
thanks for the right direction zed
Vijay Sarathi
jim mcnamara
A: 

Modern shells (POSIX compliant = modern in my view) support arithmetic operations: + - / * on signed long integer variables +/- 2147483647.

Use awk for double precision, 15 siginificant digits It also does sqrt.

Use bc -l for extended precision up to 20 significant digits.

The syntax (zed_0xff) for shell you already saw:

a=$(( 13 * 2 ))
a=$(( $2 / 2 ))
b=$(( $a - 1 ))
a=(( $a + $b ))

awk does double precision - floating point - arithmetic operations natively. It also has sqrt, cos, sin .... see:

http://people.cs.uu.nl/piet/docs/nawk/nawk_toc.html

bc has some defined functions and extended presision which are available with the -l option:

bc -l

example:

echo 'sqrt(.977)' | bc -l
jim mcnamara