Please enable JavaScript eh!

 ⌘ Web Mechanic ⌘ 

Bash Scripting


Mathematics

Bash can only do integer arithmetic
Use 'bc' for anything needing precision decimals

Performing arithmetic or mathematical operations is possible in bash, but is a bit limited and cumbersome.

c² = a² + b²

You should recognize that as the Pythagorean formula representing the sides of a right-angled triangle. And of course a b c are variables.

Doing something like that in bash is a bit of a bear. Start with something simple:

Salary=0
PerMonth=3200
NumMonths=10

Note we don't use the dollar sign $ when creating a variable, only when we use or refer to the variable again.

Salary=$((PerMonth*NumMonths))
echo $Salary
32000

Calculating the value of Salary is done using an arithmetic expansion: $(( )).

Doing the Pythagorean formula:

a=3
b=4
echo c²=$((a**2 + b**2))
c²=25

However, bash does not have an operator to do square root. To do that we need to use other means.

What can be done are these operators:

• addition, subtraction: + -
• multiplication: *
• exponentiation: **
• division: /
• modulo (integer remainder): %
• variable post-increment: var++
• variable pre-increment: ++var
• variable post-decrement: var-
• variable pre-decrement: -var
• equality: ==
• inequality: !=
• greater than: >
• less than: <
• less than or equal: <=
• greater than or equal: >=

Some alternatives are awk or bc.

See also Bash Math Operators

The Pythagorean formula above cannot be done using bash operators, but awk and bc provide a sqrt (square root) operator.

echo "Square root of "$c;echo $c | awk '{print sqrt($c)}'
Square root of 25
5

...or

echo 25 | awk '{print "Square root of",$1"="sqrt($1)}'
Square root of 25=5

...or using bc

echo 'sqrt(3^2 + 4^2)' |bc
5

If you need to use variables, they need to be double-quoted to expand them:
Unix Stackexchange

bc <<< "sqrt ($a^2 + $b^2)"
5

That used the symbol (<<<) which starts a here string: The string is expanded and fed to the program’s stdin.

To assign the result of a command to a variable we must use backticks (`):

c=`echo "sqrt($a^2+$b^2)"|bc`
echo $c
5

bc | Math with Arrays