Bash Math Operations (Bash Arithmetic) Explained {+11 Examples}

Introduction

Mathematical and arithmetic operations are essential in Bash scripting. Several automation tasks require basic arithmetic operations, such as converting CPU temperature to Fahrenheit. Implementing mathematical operations in Bash is simple and very easy to learn.

This guide teaches you how to do basic math in Bash in several ways.

Prerequisites

  • Command line/terminal access
  • .

  • A text editor for coding examples, such as nano or Vi/Vim
  • . Basic knowledge of Bash scripting. Why do you need math in Bash Scripting? Although math is not the primary purpose of

  • Bash scripting
  • ,

knowing how to do essential calculations is useful for several

use cases.

Common use cases include:

  • Adding/subtracting/multiplying/dividing
  • numbers.

  • Rounding of numbers
  • .

  • Increasing numbers and decrements
  • .

  • Conversion units
  • .

  • Floating-point calculations
  • .

  • Find percentages.
  • Work with different numerical bases (binary, octal or hexadecimal).

Depending on the automation task, basic math and arithmetic in Bash scripting help to perform a quick calculation, producing immediate results in the desired format.

Bash Mathematical Commands and Methods

Some Linux commands allow you to perform basic and advanced calculations right away. This section shows basic mathematical examples with each method.

The

preferable way to do Bash math is to use shell arithmetic expansion. The built-in capability evaluates mathematical expressions and returns the result. The syntax for arithmetic expansions

is: $((expression)) The

syntax consists of

:

  • Composite notation (()) that evaluates the expression
  • .

  • The variable operator $ to store

the result.

For example, add two numbers and echo the result: echo

$((2+3))

Arithmetic expansion notation is the preferred method when working with Bash scripts. The notation is often seen in conjunction with if statements and for loops in Bash.

awk Command

The awk command acts as a pattern expression selector. For example, to add using the awk command, use the following example statement: awk

‘BEGIN { x = 2; y = 3; print “x + y = “(x+y) }’

For variables x = 2 and y = 3, the output prints x + y = 5 in the console.

bc command

The bc command (short for basic c Alculator) is a command-line utility that represents the BC language. The program runs as an interactive program or takes standard input to perform arbitrary-precision arithmetic.

Pipe an equation from the standard input to the command to get results. For example:

echo “2+3” | bc

The output prints the result of the calculation

.

dc

command

The dc command (short for d esk calculator) is a calculator utility that supports reverse Polish notation. The program takes standard input and supports unlimited precision arithmetic.

Pipe a standard input equation into the command to get the result. For example:

echo “2 3 + p” | dc

The p in the equation sends the print signal to the dc command

. declare

Command

The declare Bash command allows integer calculations. To use declare for calculations, add the -i option. For example

: declare -i x=2 y=3 z=x+y Echo each variable to

see the results:

echo $x + $y = $z

The output prints each variable to the console

. expr command The

expr command is a legacy command-line utility for evaluating integer arithmetic. An example expr command looks like this: expr

2 + 3

Separate the numbers and operation sign with spaces and run

the command to see the result of the calculation. factor

Command

The factor command is

a command-line utility that prints the factors for any positive integer and the result is factored into prime numbers

.

For example, to print the factors of the number 100, Execution: factor 100

The output prints the factored number

. let

Command

The Bash let command performs various arithmetic, bitwise and logical operations. The built-in command works only with integers. The following example shows the syntax for the let command: let

x=2+3 | echo $x

The output prints the results

. test command

The

test command on Linux evaluates conditional expressions and is often paired with the Bash if statement. There are two variations for the test syntax: test

2 -gt 3; echo $?

Or alternatively:

[ 2 -gt 3 ]; echo $?

The test command evaluates whether two is greater than (-gt) three. If the expression is true, the result is zero (0) or one (1) if false.

Bash Arithmetic Operators Bash

offers a wide range of arithmetic operators for various calculations and evaluations. Operators work with let expansion, declare and arithmetic.

Below is a quick reference table describing Bash arithmetic operators and their functionality.

++xx++-x x+*/%**^&&|| ! &| ^~<=<>=>==!=

=How to do mathematics in

Bash Bash

offers different ways to perform mathematical calculations depending on the type of problem

.

Below are examples of some common problems that use Bash math commands or functionalities as a solution. Most examples use Bash arithmetic expansion notation. The section also covers common Bash math errors and how to solve them.

Mathematics

with integers

Arithmetic expansion notation is the simplest to use and manipulate when working with integers. For example, create an expression with variables and calculate the result immediately:

echo $((x=2, y=3, x+y))

To evaluate multiple expressions, use compound notation, store each calculation in a variable, and echo the result. For example:

((x=2, y=3, a=x+y, b=x*y, c=x**y)); echo $a, $b $c

When trying to split, keep the following in mind:

1. Division by zero (0) is impossible and yields an error.

2. Bash arithmetic expansion does not support floating-point arithmetic. When trying to split in this case, the output shows zero (0).

The result of integer division must be an integer. Bash

arithmetic expansion uses the increment and decrease of integers of style C. The operator to increase or decrease is before or after the variable, producing a different behavior.

If the operator is before the variable (++x or -x), the increment or decrease occurs before the value assignment. To see how the pre-increment works, run the following lines:

number=1 echo $((++number))

The variable is incremented and the new value is immediately available

. If the

operator is after the variable (x++ or x-), the increment or decrease occurs after the value assignment. To see how post-increment works, run the following:

number=1 echo $((number++)) echo $number

The variable remains the same and is incremented on the next use

. Floating-point arithmetic Although Bash arithmetic expansion does not support

floating-point arithmetic

, there are other ways to perform such calculations. Below are four examples that use commands or programming languages available on most Linux systems.

1. Using awk

for up to 6 decimal places: awk

‘BEGIN { x = 2.3; y = 3.2; print “x * y = “(x * y) }’

2. Using bc with -l indicator for up to 20 decimal places:

echo “2.3 * 3.2” | BC-L

3. Using Perl for up to 20 decimal places:

perl -e ‘print 2.3*3.2’

Perl often comes pre-installed on Linux systems

. 4. Using printf

and arithmetic expansion to convert

a fraction to a decimal: printf %.<precision>f “$((10**<multiplier> * <fraction>))e-<multiplier>”

Precision dictates how many decimal places, while multiplier is a power of ten. The number must be less than the multiplier. Otherwise, the formula puts trailing zeros in the result.

For example, convert

1/3 to a decimal with precision two: printf %.2f “$((10**3 * 1/3))e-3”

Avoid this method for accurate calculations and use it only for a small number of decimal places

. Calculating a Percentage

and

Rounding Below are two ways to calculate a percentage in Bash

.

1. Use printf with arithmetic expansion.

printf %.2f “$((10**4 * part/total))e-4″%

For example, calculate what percentage

is 40 out of 71: printf %.2f%% “$((10**4 * 40/71))e-4″%

Precision is limited to two decimal places, and the answer is always rounded down

. 2. Use awk with printf for better accuracy: awk ‘BEGIN { printf “%.2f%%”, (part/total*100) }’

For example, calculate how much percentage is 40 out of 71 with: awk ‘BEGIN { printf “%.2f%%”, (40/71*100) }’

The answer is rounded up if the third decimal place is greater than five, providing better accuracy.

Find a factorial

in the shell

To calculate a factorial for any number, use a recursive Bash function.

For small numbers,

Bash arithmetic expansion works well

: factorial () { if (($1 > 1)) then echo $(( $( factorial $(($1 – 1)) ) * $1 )) else echo 1 return fi } To check the factorial

of a number, use the following syntax:

factorial

5 The method is slow and has limited precision (up to factorial 20).

For greater accuracy, faster results and larger numbers, Use the bc command. For example:

echo ‘define factorial(x) {if (x>1){return x*factorial(x-1)};return 1} factorial(<number>)’ | bc

Replace <number> with the factorial number to be calculated. For example, to find the factorial of 50, use:

echo ‘define factorial(x) {if(x>1){return x*factorial(x-1)};return 1} factorial(50)’ | bc

The output prints the calculation result to the terminal.

Create a Bash calculator function

Create a simple Bash calculator function with the following code: calculate

() { printf “%s\n” “$@” | bc -l; }

The function takes user input and pipes the equation into the bc command.

Alternatively, to avoid using programs, use Bash arithmetic expansion in a function:

calculate() { echo $((“$@”)); }

Note the limitations of arithmetic expansion. Floating-point arithmetic is not available with this feature.

Save the function in the .

bashrc file so that you always have the function available in the shell

.

Use of different

arithmetic bases

By default, Bash arithmetic expansion uses base ten numbers. To change the number base, use the following format

: base#number

Where base is any integer between two and 64

.

For example, to perform a binary calculation

(base 2), use: echo $((2#1010+2#1010))

Octal calculations (base 8) use a 0 prefix as an alias. For example:

echo $((010+010))

Hexadecimal calculations (base 16) allow you to use 0x as the base prefix. For example

: echo $((0xA+0xA))

The output prints the result in base ten for any calculation

.

Convert

units

Create a simple Bash script to convert units:

1. Open a text editor, such as Vim, and create a convert.sh script. For example:

vim convert.sh

2. Paste the following code

: #!/bin/bash ## Program for foot and inch conversion echo “Enter a number to convert:” Echo Read Number $number feet to inches: Echo “$number*12” | BC-L Echo $number inches to feet: Echo “$number/12” | bc -l

The program uses Bash read to take user input and calculates the conversion from feet to inches and from inches to feet

.

3. Save the script and close: :

wq

4. Run the Bash script with:

. convert.sh

Enter a number and see the result. For different conversions, use appropriate conversion formulas.

Resolving “

bash error: value too large for base”

When working with different number bases, stay within the limits of the number base. For example, binary numbers use 0 and 1 to define numbers

: echo $((2#2+2#2)) When trying to use 2#2 as the number, an error is generated: bash: 2#2: value too large for the base (the error token is “2#2”) The

number is not the

correct format for binary use. To resolve the error, convert the number to binary to perform the calculation correctly

: echo $((2#10+2#10))

The binary number 10 is 2 in base ten

. Resolving “

syntax error: invalid arithmetic operator”

Bash arithmetic expansion notation only works for integer calculations. Try adding two floating-point numbers, for example

: echo $((2.1+2.1))

The command prints

an error: bash: 2.1+2.1: syntax error: invalid arithmetic operator (error token is “.1+2.1”) To resolve the error,

use regular integer arithmetic or a different method to calculate the equation

. Resolving “

bash error: expected integer expression”

When comparing two numbers, the test command requires integers. For example, try the following command

: [ 1 -gt 1.5 ]

The output prints an

error: bash: [: 1.5: expected integer expression

Resolve the error by comparing integer values.

Conclusion

You know how to do Bash arithmetic and various calculations through Bash scripts

.

For more advanced scientific calculations, use Python in conjunction with SciPy, NumPy, and other libraries.