Bash calculate and Arithmetic Operators

Shell Scripting

When the shell encounters $(( expression )), it evaluates expression and places the result on the command line; expression is an arithmetic expression. Besides the four basic arithmetic operations of addition, subtraction, multiplication, and division, its most used operator is % (modulo, the remainder after division).

$ sa "$(( 1 + 12 ))" "$(( 12 * 13 ))" "$(( 16 / 4 ))" "$(( 6 - 9 ))"

:13:

:156:

:4:

:-3:

The arithmetic operators (see Tables 4-1 and 4-2) take the same precedence that you learned in school (basically, that multiplication and division are performed before addition and subtraction), and they can be grouped with parentheses to change the order of evaluation:

$ sa "$(( 3 + 4 * 5 ))" "$(( (3 + 4) * 5 ))"

:23:

:35:

The modulo operator, %, returns the remainder after division:

$ sa "$(( 13 % 5 ))"

:3:

Converting seconds (which is how Unix systems store times) to days, hours, minutes, and seconds involves division and the modulo operator, as shown in Listing 1.

Listing 1. secs2dhms, Convert Seconds (in Argument $1) to Days, Hours, Minutes, and Seconds

secs_in_day=86400 
secs_in_hour=3600 
mins_in_hour=60 
secs_in_min=60

days=$(( $1 / $secs_in_day ))

secs=$(( $1 % $secs_in_day ))

printf "%d:%02d:%02d:%02d\n" "$days" "$(($secs / $secs_in_hour))" \

"$((($secs / $mins_in_hour) %$mins_in_hour))" "$(($secs % $secs_in_min))"

If not enclosed in double quotes, the results of arithmetic expansion are subject to word splitting.

Operator     Description

- +            Unary minus and plus

! ~            Logical and bitwise negation

* /    %        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

= *= /= %= += -= <<= >>= &= ^= |=     Assignment

**            Exponentiation

id++ id--        Variable post-increment and post-decrement

++id –-id        Variable pre-increment and pre-decrement

expr ? expr1 : expr2     Conditional operator

expr1 , expr2         Comma

In case of any ©Copyright or missing credits issue please check CopyRights page for faster resolutions.

Leave a Reply