shell scripting arithmetic operations shell scripting arithmetic operations unix unix

shell scripting arithmetic operations


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


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


The precision and range of shell builtin $(( <expr> )) depends on the platform. On a 32-bit platform it's limited to 32-bit integers (unlike expr, which appears to support larger integers in a way that appears to be independent of platform).

(N.B - beware that while ^ is a valid operator in most shells, it does not mean 'to the power of', but rather XOR.)

Also - some shells are more forthcoming in this regard. Zsh, for example, allows floating point operations, such as $(( 10/3.0 ))