Let Bash do the math: Doing calculations using that bash

Have you ever wanted to “just do some math” without much fuss? I noticed a while ago (but haven’t really used it since) that bash (born again shell) has, amongst many other evaluations, an arithmetic one. Using the syntax $((expression)) you can evaluate the expression to arithmetically. Operations allowed are quite a few. From man bash:

ARITHMETIC EVALUATION
The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their precedence, asso ciativity, and values are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence.

       id++ id--   variable post-increment and post-decrement
       ++id --id   variable pre-increment and pre-decrement
       - +             unary minus and plus
       ! ~             logical and bitwise negation
       **              exponentiation
       * / %         multiplication, division, remainder
       + -             addition, subtraction
       <>       left and right bitwise shifts
       =
                        comparison
       == !=       equality and inequality
       &               bitwise AND
       ^               bitwise exclusive OR
       |                bitwise OR
       &&             logical AND
       ||              logical OR
       expr?expr:expr
                        conditional operator
       = *= /= %= += -= <>= &= ^= |=
                        assignment
       expr1 , expr2
                        comma

Shell variables are allowed as operands; parameter expansion is performed before the expression is evaluated. Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax. A shell variable that is null or unset evaluates to 0 when referenced by name without using the parameter expansion syntax. The value of a variable is evaluated as an arithmetic expression when it is ref erenced, or when a variable which has been given the integer attribute using declare -i is assigned a value. A null value evaluates to 0. A shell variable need not have its integer attribute turned on to be used in an expression.

Constants with a leading 0 are interpreted as octal numbers. A leading 0x or 0X denotes hexadecimal. Other wise, numbers take the form [base#]n, where base is a decimal number between 2 and 64 representing the arith metic base, and n is a number in that base. If base# is omitted, then base 10 is used. The digits greater than 9 are represented by the lowercase letters, the uppercase letters, @, and _, in that order. If base is less than or equal to 36, lowercase and uppercase letters may be used interchangeably to represent numbers between 10 and 35.

25 Comments

  1. linux vps said,

    Monday, 5th Aug 2013 at 12:51

    Howdy this is kinda of off topic but I was wanting to know if blogs use WYSIWYG editors or if you have to manually code with HTML. I’m starting a blog soon but have no coding knowledge so I wanted to get advice from someone with experience. Any help would be enormously appreciated!|

  2. www said,

    Wednesday, 3rd Oct 2012 at 15:41

    katappe, change $(($variable*5)) to something like $((($variable)*5)). you should provide extra () so that the results of the variable is multiplied by 5. not sure if $ should be inside, but it’s something like that

  3. ktappe said,

    Monday, 23rd Apr 2012 at 20:21

    Not very useful unless you show the syntax needed to multiply variables. For example, echo $((2*5)) works, but echo $(($variable*5)) doesn’t, nor does echo $((variable*5)). Without this info, what possible use is this tutorial? Who would ever script the multiplication of constants??

  4. Just-an-example said,

    Tuesday, 10th Apr 2012 at 15:39

    Here a small example: echo $((1+1))

  5. Brian said,

    Friday, 6th Apr 2012 at 20:59

    This tutorial blows. Good job giving an example. What do I type into the command line to do 1+1?

  6. sebas said,

    Monday, 2nd Apr 2012 at 03:45

    Bash doesn’t accept calculations with decimals, but zsh does

    To avoid to have to always type $(()) we can put an alias in ~/.bashrc (ou .zshrc)
    alias calc=’echo -n \> ; read X_CALC ; echo $(($X_CALC))’

    Another solution is to put in ~/.bashrc (ou .zshrc)
    calcc(){ awk “BEGIN{ print $* }” ;}
    # usage : calcc 2^(3+2 ) or “2**(3+2)” (we must escape * and **)

  7. A. L. said,

    Friday, 23rd Dec 2011 at 18:22

    Thanks for the tutorial! It came up as one of the first few links when I searched Google for ‘bash shell math’, and it was exactly what I needed!

  8. Saturday, 10th Dec 2011 at 22:20

    nice tutorial!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: