Bash Arithmetic Operators

In Bash, you can perform arithmetic operations using various arithmetic operators. Here are the commonly used arithmetic operators in Bash:

  1. Addition (+): Adds two values together. Example: result=$((2 + 3))
  2. Subtraction (-): Subtracts one value from another. Example: result=$((10 - 5))
  3. Multiplication (*): Multiplies two values. Example: result=$((4 * 6))
  4. Division (/): Divides one value by another. Example: result=$((20 / 4))
  5. Modulo (%): Computes the remainder of division. Example: result=$((15 % 6))
  6. Increment (++) and Decrement (–): Increases or decreases the value of a variable by 1. Example:
a=5
a=$((a + 1))  # Increment by 1
a=$((a - 1))  # Decrement by 1
  1. Exponentiation (**): Raises one value to the power of another. Example: result=$((2 ** 3))
  2. Arithmetic expressions within double parentheses (( )): Allows complex arithmetic expressions and evaluation. Example: result=$(( (5 + 3) * 2 - 1 ))
  3. Arithmetic expansion using $(( )): Evaluates arithmetic expressions within a $(( )) construct. Example: result=$(($a + $b))

Here’s an example that combines different arithmetic operations:

#!/bin/bash

a=5
b=3

result1=$((a + b))
result2=$((a * b))
result3=$((a / b))

echo "Result 1: $result1"
echo "Result 2: $result2"
echo "Result 3: $result3"

When you run this script, it will output:

Result 1: 8
Result 2: 15
Result 3: 1

These arithmetic operators allow you to perform mathematical calculations within Bash scripts. You can use them to manipulate numeric values, perform calculations, and make decisions based on arithmetic comparisons.

Leave a Comment

Your email address will not be published. Required fields are marked *