One thing that often confuses new users to the Unix / Linux shell, is

how to do (even very simple) maths. In most languages, x = x + 1 (or

even x++) does exactly what you would expect. The Unix/Linux shell is

different,however. It doesn’t have any built-in mathematical operators

for variables. It can do comparisons, but maths isn’t supported, not

even simple addition.

Shell script variables are by default treated as strings,not numbers,

which adds some complexity to doing math in shell script. To keep with

script programming paradigm and allow for better math support, langua-

ges such Perl or Python would be better suited when math is desired.

However, it is possible to do math with shell script.In fact, over the

years, multiple facilities have been added to Unix to support working

with numbers.

You can do maths using any one of the following methods.

**1. Using expr command**

2 Using $(()) construct.

3 Using let command

4 Using bc command.

5 Using $[] construct.

##### expr command:

expr command performs arithmetic operations on integers. It can

perform the four basic arithmetic operations, as well as the modulus

(remainder function).

$ expr 5 + 10

15

$ a=10 b=5

$ expr $a + $b

15

$ expr $a / $b

2

$ expr $a * $b

expr: syntax error

$ expr $a \* $b

50

The operand, be it +,-,* etc., must be enclosed on either side by

whitespace. Observe that the multiplication operand (*) has to be

escaped to prevent the shell from interpreting it as the filename meta

character. Since expr can handle only integers, division yields only

the integral part.

expr is often used with command substitution to assign a variable.

For example, you can set a variable x to the sum of two numbers:

$ x=`expr $a + $b`

$ echo $x

15

**Note:** As you can see, for expr, you must put spaces around the

arguments: "expr 123+456" doesn’t work. "expr 123 + 456" works.

##### With double parentheses: $(()) and (())

In bash version 3.2 and later you can (and should) use $(()) and (())

for integer arithmetic expressions. You may have may not have spaces

around the operators, but you must not have spaces around the equal

sign, as with any bash variable assignment.

$ c=$(($a+9))

$ echo $c

19

$ c=$((a+9)) #Also correct, no need of $ sign.

$ c=$((a + 9)) #Also correct, no restriction on spaces.

$ c= $((a + b)) #Incorrect, space after assignment operator.

You may also use operations within double parentheses without

assignment.

$ ((a++))

$ echo $a

11

$ ((a+=1)) ; echo $a

12

$ ((d=a+b+9)) ; echo $d

26

$ ((a+=$b)) #Correct

$ (($a+=1)) #Incorrect

##### let command:

The let command carries out arithmetic operations on variables. In

many cases, it functions as a less complex version of expr command.

As you can see, it is also a little picky about spaces, but it wants

the opposite of what expr wanted. let also relaxes the normal rule of

needing a $ in front of variables to be read.

$ let a=10 # Same as 'a=11'

$ let a=a+5 # Equivalent to let "a = a + 5"

# Quotes permit the use of spaces in variable assignment. (Double

# quotes and spaces make it more readable.)

$ let a=$a + 5 # Without quotes spaces not allowed.

bash: let: +: syntax error: operand expected (error token is "+")

You need to use quotes if you want to use spaces between tokens of

the expression, for example

**$ let "a = a + 5";echo $a**

20

The only construct that is more convenient to use with let is incre-

ment such as

**$ let a++ ; echo $a # as well as to ((i++))**

16

##### bc: THE CALCULATOR

Bash doesn't support floating point arithmetic. The obvious candidate

for adding floating point capabilities to bash is **bc**. bc is not only a

command, it also a pseudo-programming language featuring arrays,funct-

ions,conditional(if) and loops(for and while). It also comes with a

library for performing scientific calculations. It can handle very,

very large numbers. If a computation results in a 900 digit number, bc

will show each and every digit. But you have to treat the variables as

strings.

Here is what happens when we try to do floating point math with the

shell:

$ let a=12.5

bash: let: a=12.5: syntax error: invalid arithmetic operator (error

token is ".5")

$ ((b=1*0.5))

bash: ((: b=1*0.5: syntax error: invalid arithmetic operator (error

token is ".5")

I can't explain everything about bc here, it needs another post.

But I will give some examples here.

Most of the bellow examples follow a simple formula:

$ echo '57+43' | bc

100

$ echo '57*43' | bc

2451

$ echo '6^6' | bc # Power

46656

$ echo '1.5*5'|bc # Allows floating point math.

7.5

##### $[] construct:

$ x=85

$ y=15

$ echo $[x+y]

100

$ echo $[x/y]

5

$ c=$[x*y]

$ echo $c

1275

Working of above methods shell dependent. Bash shell supports all 5

methods. Following shell script demonstrates above methods.

#!/bin/bash

# SCRIPT: basicmath.sh

# USAGE: basicmath.sh

# PURPOSE: Addition, Subtraction, Division and Multiplication of

# two numbers.

# \\\\ ////

# \\ - - //

# @ @

# ---oOOo-( )-oOOo---

#

#####################################################################

# Variable Declaration #

#####################################################################

clear #Clears Screen

Bold="\033[1m" #Storing escape sequences in a variable.

Normal="\033[0m"

echo -e "$Bold Basic mathematics using bash script $Normal\n"

items="1. ADDITTION

2. SUBTRACTION

3. MULTIPLICATION

4. DIVISION

5. EXIT"

choice=

#####################################################################

# Define Functions Here #

#####################################################################

# If didn't understand these functions, simply remove functions and

# its entries from main script.

exit_function()

{

clear

exit

}

#Function enter is used to go back to menu and clears screen

enter()

{

unset num1 num2

ans=

echo ""

echo -e "Do you want to continue(y/n):\c"

stty -icanon min 0 time 0

# When -icanon is set then one character has been received.

# min 0 means that read should read 0 characters.

# time 0 ensures that read is terminated the moment one character

# is hit.

while [ -z "$ans" ]

do

read ans

done

#The while loop ensures that so long as at least one character is

# not received **read** continue to get executed

if [ "$ans" = "y" -o "$ans" = "Y" ]

then

stty sane # Restoring terminal settings

clear

else

stty sane

exit_function

fi

}

#####################################################################

# Main Starts #

#####################################################################

while true

do

echo -e "$Bold \tPROGRAM MENU $Normal\n"

echo -e "\t$items \n"

echo -n "Enter your choice : "

read choice

case $choice in

1) clear

echo "Enter two numbers for Addition : "

echo -n "Number1: "

read num1

echo -n "Number2: "

read num2

echo "$num1 + $num2 = `expr $num1 + $num2`"

enter ;;

2) clear

echo "Enter two numbers for Subtraction : "

echo -n "Number1: "

read num1

echo -n "Number2: "

read num2

echo "$num1 - $num2 = $((num1-num2))"

enter ;;

3) clear

echo "Enter two numbers for Multiplication : "

echo -n "Number1: "

read num1

echo -n "Number2: "

read num2

echo "$num1 * $num2 = `echo "$num1*$num2"|bc`"

enter ;;

4) clear

echo "Enter two numbers for Division : "

echo -n "Number1: "

read num1

echo -n "Number2: "

read num2

let div=num1/num2

echo "$num1 / $num2 = $div"

enter ;;

5) exit_function ;;

*) echo "You entered wrong option, Please enter 1,2,3,4 or 5"

echo "Press enter to continue"

read

clear

esac

done

**OUTPUT:**

[venu@localhost ~]$ sh basicmath.sh

Basic mathematics using bash script

PROGRAM MENU

1. ADDITTION

2. SUBTRACTION

3. MULTIPLICATION

4. DIVISION

5. EXIT

Enter your choice : 1

Enter two numbers for Addition :

Number1: 123

Number2: 456

123 + 456 = 579

Do you want to continue(y/n):y

PROGRAM MENU

1. ADDITTION

2. SUBTRACTION

3. MULTIPLICATION

4. DIVISION

5. EXIT

Enter your choice : 3

Enter two numbers for Multiplication :

Number1: 12.5

Number2: 2

12.5 * 2 = 25.0

Do you want to continue(y/n):n

## Sunday, December 26, 2010

Posted by venu k

15 comments | 7:36 AM

Subscribe to:
Post Comments (Atom)

Excellent pieces. Keep posting such kind of information on your blog. I really impressed by your blog.

ReplyDeleteVee Eee Technologies

good stuff please continue uploading such information since it is vital for bash scripting

ReplyDeletehow to do addition,subtraction,multiplication of the complex number in shell script??????

ReplyDelete$ let a=10 # Same as 'a=11'

ReplyDeleteWhy does let add 1?

The only portable method without using an external command is:

ReplyDelete$(( _expression_ ))

Superb article. Keep posting.

ReplyDeleteFor more details on bc command check the below link:

bc command examples in unix

i need for finding power of number like in c pow(x,n) how to do this in shell scripting ?

ReplyDeleteVery good posting. Good one

ReplyDeleteGood one

ReplyDeleteThank you very much. This is very good.

ReplyDeleteyou better use bc -l

ReplyDeletei.e.:

echo "$num1 * $num2 = `echo "$num1*$num2"|bc -l`"

echo "$num1 / $num2 = `echo "$num1/$num2"|bc -l`"

That lets your script to handle floating points

:)

will the below work, if no, why not

ReplyDelete`expr ($avail_space - ($reqd_space \* 1024))/1024`

INTERNATIONAL CONCEPT OF WORK FROM HOME

ReplyDeleteWork from home theory is fast gaining popularity because of the freedom and flexibility that comes with it. Since one is not bound by fixed working hours, they can schedule their work at the time when they feel most productive and convenient to them. Women & Men benefit a lot from this concept of work since they can balance their home and work perfectly. People mostly find that in this situation, their productivity is higher and stress levels lower. Those who like isolation and a tranquil work environment also tend to prefer this way of working. Today, with the kind of communication networks available, millions of people worldwide are considering this option.

Women & Men who want to be independent but cannot afford to leave their responsibilities at home aside will benefit a lot from this concept of work. It makes it easier to maintain a healthy balance between home and work. The family doesn't get neglected and you can get your work done too. You can thus effectively juggle home responsibilities with your career. Working from home is definitely a viable option but it also needs a lot of hard work and discipline. You have to make a time schedule for yourself and stick to it. There will be a time frame of course for any job you take up and you have to fulfill that project within that time frame.

There are many things that can be done working from home. A few of them is listed below that will give you a general idea about the benefits of this concept.

Baby-sitting

This is the most common and highly preferred job that Women & Men like doing. Since in today's competitive world both the parents have to work they need a secure place to leave behind their children who will take care of them and parents can also relax without being worried all the time. In this job you don't require any degree or qualifications. You only have to know how to take care of children. Parents are happy to pay handsome salary and you can also earn a lot without putting too much of an effort.

Nursery

For those who have a garden or an open space at your disposal and are also interested in gardening can go for this method of earning money. If given proper time and efforts nursery business can flourish very well and you will earn handsomely. But just as all jobs establishing it will be a bit difficult but the end results are outstanding.

Freelance

Freelance can be in different wings. Either you can be a freelance reporter or a freelance photographer. You can also do designing or be in the advertising field doing project on your own. Being independent and working independently will depend on your field of work and the availability of its worth in the market. If you like doing jewellery designing you can do that at home totally independently. You can also work on freelancing as a marketing executive working from home. Wanna know more, email us on workfromhome.otr@gmail.com and we will send you information on how you can actually work as a marketing freelancer.

Internet related work

This is a very vast field and here sky is the limit. All you need is a computer and Internet facility. Whatever field you are into work at home is perfect match in the software field. You can match your time according to your convenience and complete whatever projects you get. To learn more about how to work from home, contact us today on workfromhome.otr@gmail.comand our team will get you started on some excellent work from home projects.

Diet food

Since now a days Women & Men are more conscious of the food that they eat hence they prefer to have homemade low cal food and if you can start supplying low cal food to various offices then it will be a very good source of income and not too much of efforts. You can hire a few ladies who will help you out and this can be a good business.

Thus think over this concept and go ahead.

Great one and it seems you have put a lot of time and effort in it. Keep posting this kind of post. Users will definitely like it.

ReplyDeletePlease see this : How System.out.println() works in java.

A special thanks for this informative post. I definitely learned new stuff here I wasn't aware of !

ReplyDelete