Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shell scripting arithmetic operations

Tags:

shell

unix

ksh

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?

like image 836
Vijay Avatar asked Jun 10 '10 05:06

Vijay


People also ask

How does bash calculate arithmetic operations?

The oldest command for doing arithmetic operations in bash is 'expr'. This command can work with integer values only and prints the output directly in the terminal. You have to use space with each operand when you want to use the 'expr' command to do any mathematical operations. Create a bash file named expr.

What are the 4 types of arithmetic operators?

These operators are + (addition), - (subtraction), * (multiplication), / (division), and % (modulo).

Can bash script do math?

Math and arithmetic operations are essential in Bash scripting. Various automation tasks require basic arithmetic operations, such as converting the CPU temperature to Fahrenheit. Implementing math operations in Bash is simple and very easy to learn.


2 Answers

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
like image 101
jim mcnamara Avatar answered Sep 28 '22 12:09

jim mcnamara


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

like image 41
zed_0xff Avatar answered Sep 28 '22 12:09

zed_0xff