• Welcome to Bashguru

    Linux is one of popular version of UNIX operating System. It is open source as its source code is freely available. It is free to use. Linux was designed considering UNIX compatibility. It's functionality list is quite similar to that of UNIX and become very popular over the last several years. Our Basic motive is to provide latest information about Linux Operating system.

  • Python Programming

    Python is a comparatively simple programming language, compared to c++. Although some of the benefits of c++ are abstracted away in python, they are replaced with an overall easier to learn language with many “intuitive” features. For this reason it is common and recommended by most professionals that people new to programming start with python.

  • Perl Programming

    Perl is an open-source, general-purpose interpreted programming language. Used often for CGI, Perl is also used for graphics programming, system administration, network programming, finance, bioinformatics, and other applications. The Perl languages borrow features from other programming languages including C, shell scripting (sh), AWK, and sed. They provide powerful text processing facilities without the arbitrary data-length limits of many contemporary UNIX command line tools, facilitating easy manipulation of text files.

  • Android

    Android is an operating system based on the Linux kernel, and designed primarily for touch screen mobile devices such as smart phones and tablet computers. Android is a Linux-based software system, and similar to Linux, is free and open source software. This means that other companies can use the Android operating developed by Google and use it in their mobile devices.Android gives you a world-class platform for creating apps and games for Android users everywhere, as well as an open marketplace for distributing to them instantly.

Sunday, December 26, 2010

Posted by venu k
94 comments | 7:36 AM

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
$ a=10 b=5
$ expr $a + $b
$ expr $a / $b
$ expr $a * $b
expr: syntax error
$ expr $a \* $b

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

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

$ ((a++))
$ echo $a
$ ((a+=1)) ; echo $a
$ ((d=a+b+9)) ; echo $d
$ ((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

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++))


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

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

$ 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
$ echo '57*43' | bc
$ echo '6^6' | bc # Power
$ echo '1.5*5'|bc # Allows floating point math.

$[] construct:

$ x=85
$ y=15
$ echo $[x+y]
$ echo $[x/y]
$ c=$[x*y]
$ echo $c

Working of above methods shell dependent. Bash shell supports all 5
methods. Following shell script demonstrates above methods.

# 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.

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

items="1. ADDITTION
5. EXIT"


# Define Functions Here #

# If didn't understand these functions, simply remove functions and
# its entries from main script.


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

unset num1 num2
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" ]
read ans

#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" ]
stty sane # Restoring terminal settings
stty sane

# Main Starts #

while true
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"


[venu@localhost ~]$ sh basicmath.sh

Basic mathematics using bash script



Enter your choice : 1

Enter two numbers for Addition :
Number1: 123
Number2: 456
123 + 456 = 579

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



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


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

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

  3. how to do addition,subtraction,multiplication of the complex number in shell script??????

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

    Why does let add 1?

  5. The only portable method without using an external command is:

    $(( _expression_ ))

  6. Superb article. Keep posting.
    For more details on bc command check the below link:
    bc command examples in unix

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

  8. Very good posting. Good one

  9. Thank you very much. This is very good.

  10. you better use bc -l
    echo "$num1 * $num2 = `echo "$num1*$num2"|bc -l`"

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

    That lets your script to handle floating points

  11. will the below work, if no, why not

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

    Work 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.

    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.

    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 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.

  13. 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.
    Please see this : How System.out.println() works in java.

    1. The link given about has expired. So admin please fix it or delete it. I have found another article that gives the same info : System.out.println() in java. It is explained quite good there.

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

  15. Thanks for your informative article. Java is most popular programming language used for creating rich enterprise, desktop and web applications. Keep on updating your blog with such informative post. Java Course in Chennai

  16. That was a very informative post. Thank you so much. Keep posting more.
    QTP training institutes in Chennai

  17. Great tutorial. I really learned some new things here. So thanks.

    web design training institute in Chennai

  18. Oracle DBA Training in Chennai
    Thanks for sharing this informative blog. I did Oracle DBA Certification in Greens Technology at Adyar. This is really useful for me to make a bright career..

  19. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing..
    Websphere Training in Chennai

  20. Data warehousing Training in Chennai
    I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly..

  21. Selenium Training in Chennai
    Wonderful blog.. Thanks for sharing informative blog.. its very useful to me..

  22. Oracle Training in chennai
    Thanks for sharing such a great information..Its really nice and informative..


  23. SAP Training in Chennai
    This post is really nice and informative. The explanation given is really comprehensive and informative..

  24. This information is impressive..I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic
    Android Training In Chennai In Chennai

  25. Pretty article! I found some useful information in your blog, it was awesome to read,
    thanks for sharing this great content to my vision, keep sharing..
    Unix Training In Chennai

  26. I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision, keep sharing..
    SalesForce Training in Chennai

  27. Excellent information with unique content and it is very useful to know about the information based on blogs. Hadoop Training in Chennai

  28. I found some useful information in your blog,it was awesome to read, thanks for sharing this great content to my vision, keep sharing..selenium Training in Chennai

  29. Really awesome blog. Your blog is really useful for me. Thanks for sharing this informative blog. Keep update your blog.SAP Training in Chennai

  30. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.. Android Training in Chennai

  31. This comment has been removed by the author.

  32. This comment has been removed by the author.

  33. This comment has been removed by the author.

  34. This comment has been removed by the author.

  35. Wonderful tips, very helpful well explained. Your post is definitely incredible. I will refer this to my friend.SalesForce Training in Chennai

  36. very nice blogs!!! i have to learning for lot of information for this sites...Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.Oracle DBA Training in Chennai

  37. This is really an awesome article. Thank you for sharing this.It is worth reading for everyone. Visit us:Oracle Training in Chennai


  38. I have read your blog, it was good to read & I am getting some useful info's through your blog keep sharing... Informatica is an ETL tools helps to transform your old business leads into new vision. Learn Informatica training in chennai from corporate professionals with very good experience in informatica tool.
    Best Informatica Training In Chennai|Informatica training center in Chennai

  39. Excellent information with unique content and it is very useful to know about the information based on blogs.
    Hadoop Training In Chennai | oracle apps financials Training In Chennai | advanced plsql Training In Chennai

  40. Rajasthan Gram Panchayat 2252 Sathin Recruitment 2015-16

    Very nice and useful information, Thanks for sharing..... Thank you sir ........

  41. Thanks for your informative post. Your info graphic helped me to create my first blog on blogger platform. Please assist me whether my blog on Web designing course in Chennai is eligible for AdSense.

  42. Web technology has evolved so much in the past years and it is being the part of a company's growth for a long time(Web designing course in chennai). It is explicitly printed in the above content. I really love the way you have started writing this article. It is the skill that every blogger require. Thanks for sharing this in here once again. Keep blogging like this(Web design training).

  43. new horizon security services manassas reviews Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!

  44. Latest Govt Bank Jobs 2016

    I have visited this blog first time and i got a lot of informative data from here which is quiet helpful for me indeed. .......................

  45. I think comments can help you get feedback from your readers and see if you are blogging efforts pay off. If there are some posts that you don't want the comments to be made on you can always close the comments.
    Order Safest Dianabol Online

  46. parking lot sweeping Virginia Atlantic Sweeping & Cleaning: Sweeping services, pressure washing, porter services in Virginia, Maryland & DC. Since 1977 best in class in parking lot sweeping & more

  47. Excellent Post, I welcome your interest about to post blogs. It will help many of them to update their skills in their interesting field.
    sas training in Chennai|sas course in Chennai|sas training institute in Chennai

  48. This comment has been removed by the author.

  49. Responsive desing can yield a very good revenue to a business. It has been discovered since the usage of multiple devices increase. The content furnished above too tells the same. Thanks for sharing this information in here. Please keep bloging content like this.

    Web designing course in chennai | Web designing courses | PHP Training in Chennai

  50. Dear admin, The way you have explained the concept is mezmerizing. Thank you so much for sharing tis worth able content with us. The concept taken here will be useful for my future programs and i will surely implement them in my study. Keep blogging article like this.

    JAVA Training in Chennai | Best JAVA Training in Chennai | Salesforce training in chennai

  51. Thanks for sharing your ideas. It’s really useful for me. Selenium is an automation testing tool used for web applications. I did Selenium Training in Chennai at besant technologies. It’s useful for me to make a bright career in IT industry.

  52. Crazy Bulk Australia 100% Safe and Legal Steroids

    Crazy Bulk is 100% safe and legal alternate steroids available in market right now. With 100% success rate and excellent muscle building effects from day 1

  53. Thanks for your post; selenium is most trusted automation tool to validate web application and browser. This tool provides precise and complete information about a software application or environment. Selenium Training in Chennai | Selenium Course in Chennai | Best Selenium training institute in Chennai

  54. Math in shell scripts good topic i read this and its gives me great info and how to solve my question thanks for sharing law school personal statement editing .

  55. Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
    Informatica Training In Chennai
    Hadoop Training In Chennai
    Oracle Training In Chennai
    SAS Training In Chennai

  56. 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
    The Investment Banking School

  57. I'am planning to join Oracle certified course. I want some expert advice whether i should go for it or not.
    oracle training in chennai|FITA Chennai


  58. Write a Shell Script that can multiply individual Digits of a Number. Let‟s suppose user input is “3312”, Output should be 3*3*1*2 = 18. If the input contains „0‟ digit in it at any place then program should ask to re try with another number.

  59. Most popular, industries-recognize certification that required complete Selenium training course & hand-on experience in
    Selenium Training in Chennai

  60. With the greater part of the negative articles about oil added substances, which have been composed and bolstered broadly by specific vested parties, its opportunity to inform the genuine truth regarding oil added substances. Much of the time they perform a positive capacity and with standard use can give various advantages to vehicles and hardware. As well; in addition

  61. Bed Bug Control Leesburg VA Just stumbled across your blog and was instantly amazed with all the useful information that is on it. Great post, just what i was looking for and i am looking forward to reading your other posts soon!

  62. Thanks for the codings.It will be helpful for Unix and Linux.Please keep updating us.

    Hadoop training in chennai

  63. Angular Js Online training at Online IT Guru with 7+ years of hands on exp. We provide training in Hyderabad and USA. Angular JS is a powerfull JavaScript Frame work.contact:9885991924.
    anjular js online training
    MS.net ONline training

  64. India Exam Results 2016. JEE Mains Results, Advanced JEE Results, 10th Class Results SSC Results 2016, Intermediate Results 2016 Manabadi Schools 9 Results 2016 Check your Results and Marks.
    SSC Results 2016
    JEE Mains Results 2016
    ICSE Results 2016
    AP SSC Results 2016
    Telangana SSC Results 2016
    CBSE 10th Class Results
    Intermediate Results 2016

  65. These scripts and formulas i also use in math and this article give me good idea and also tell how to include in math thanks for share it statement of purpose engineering .

  66. if I add two no with leading 0 ex $(( 51238400 + 062301 )) iam getting absurd answer(51264193) wrong. expected is 51300701
    where as expr 51238400 + 062301 result 51300701.
    can some one help me why above one is causing issue.

  67. I really enjoyed your article, Thanks for sharing information about cloud, it’s a useful technology helps to store and access the data over the internet. There are so many features in cloud; if you are getting training you will become familiar with the whole concept of cloud in soon time.
    cloud computing training in chennai|Cloud Computing Courses

  68. HTML5 is the recently arrived most trending technology that has bright future. If you are interested in studying HTML5 training visit this website.
    html5 training in chennai | html5 training chennai | html5 course in chennai

  69. Informatica is one of the most trusted and effective ETL software which is known globally. Informatica is one data warehousing ETL tool. Informatica ha very go opportuities for job across the world.
    informatica training in chennai | informatica training institute in Chennai | informatica classes in Chennai

  70. Thanks with regards to exposing an exceedingly very helpful plus helpful webpage.Guerrilla Advertising

  71. Nowadays, most of the businesses rely on cloud based CRM tool to power their business process. They want to access the business from anywhere and anytime. In such scenarios, salesforce CRM will ensure massive advantage to the business owners.
    Salesforce Administrator 201 Training in Chennai|Salesforce Administrator 211 Training in Chennai|Salesforce Training in Chennai

  72. Wonderful post. Happy to visit your blog. Thanks for sharing.

    Web Application Development Company in Chennai


  73. The war between humans, orcs and elves continues earn to die . Lead your race through a series of epic battles, using your crossbow to fend off foes and sending out units to destroy castleshappy wheels . Researching and upgrading wisely will be crucial to your success! There are 5 ages total and each one will bring you new units to train to fight in the war for you cause.
    earn to die 2
    Whatever you do, don’t neglect your home base because you cannot repair it and once it is destroyed, you lose! Age of War is the first game of the series and really sets the tone for the Age of War games . Also try out the Age of Defense series as it is pretty similar.
    In this game, you start at the cavern men’s age, then evolvetank trouble ! There is a total of 5 ages, each with its units and turrets. Take control of 16 different units and 15 different turrets to defend your base and destroy your enemy.
    The goal of the game also differs depending on the level. In most levels the goal is to reach a finish line or to collect tokens. Many levels feature alternate or nonexistent goals for the player. The game controls are shown just under gold miner. Movement mechanisms primarily include acceleration and tilting controls. cubefield
    It consists of a total of 17 levels and the challenge you face in each level increases as you go up. unfair mario The game basically has a red ball that has to be moved across the various obstacles in its path to the goal. slitherio

  74. To keep ourselves up to date with the current trend is not an easy task in IT. But we can, through quality and worth able content like this. Thanks for sharing this web page. Please write more articles like this in future.
    PHP training in Chennai | PHP course in Chennai

  75. parking lot sweeping Virginia Atlantic Sweeping & Cleaning: Sweeping services, pressure washing, porter services in Virginia, Maryland & DC. Since 1977 best in class in parking lot sweeping & more

  76. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it. The angular js programming language is very popular which are most widely used.
    AngularJS Training in Chennai | Angularjs training Chennai


  77. Great! Thanks for sharing the information. That is very helpful for increasing my knowledge in this fiel
    Red Ball | | duck life | Slitherio
    Red Ball 2 | Red Ball 3 | Red Ball 4

  78. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    SAS Training in Chennai | SAS Course in Chennai

  79. nice ...

    Informatica training, in the recent times has acquired a wide scope of popularity amongst the youngsters at the forefront of their career.
    Informatica online training in hyderabad

  80. Awesome Post! I like writing style, how you describing the topics throughout the post. I hope many web reader will keep reading your post at the end, Thanks for sharing your view.
    PHP Training in Chennai|PHP Course in Chennai|PHP Training Institute in Chennai