</>
Skip to content
Bash lessons (8/29)

Bash — Numbers

Arithmetic operations

#!/bin/bash

a=10
b=3

echo "Add: $((a + b))"    # 13
echo "Sub: $((a - b))"    # 7
echo "Mul: $((a * b))"    # 30
echo "Div: $((a / b))"    # 3
echo "Mod: $((a % b))"    # 1

Increment and decrement

#!/bin/bash

x=5
x=$((x + 1))  # 6
((x++))        # 7
((x--))        # 6
echo "$x"

Comparison

#!/bin/bash

a=10
b=20

[ $a -eq $b ] && echo "Equal"
[ $a -ne $b ] && echo "Not equal"
[ $a -gt $b ] && echo "Greater"
[ $a -lt $b ] && echo "Less"
[ $a -ge $a ] && echo "Greater or equal"
[ $a -le $a ] && echo "Less or equal"

Floating point (bc)

#!/bin/bash

a=3.14
b=2.0

result=$(echo "$a * $b" | bc)
echo "Result: $result" # 6.28

result=$(echo "scale=2; $a / $b" | bc)
echo "Division: $result" # 1.57

Number formatting

#!/bin/bash

printf "%d\n" 42       # 42
printf "%05d\n" 42     # 00042
printf "%f\n" 3.14159  # 3.141590
printf "%.2f\n" 3.14159 # 3.14
printf "%e\n" 100000   # 1.000000e+05
printf "%x\n" 255      # ff
printf "%o\n" 255      # 377

Random numbers

#!/bin/bash

# Random 0-32767
echo $RANDOM

# Random in range
min=1
max=100
range=$((max - min + 1))
random=$((RANDOM % range + min))
echo "Random: $random"

Mini Practice

Write Bash code that:

  1. Performs all arithmetic operations
  2. Compares two numbers
  3. Uses bc for floating-point math
  4. Formats numbers with printf

Up Next

In the next lesson, you'll learn about Arrays — working with arrays in Bash.

Related Topics

Frequently Asked Questions about Numbers

What is Numbers in Bash?

Numbers is a fundamental concept in Bash. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Numbers?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Numbers.

Why is Numbers important in Bash?

Numbers is essential for Bash development. Understanding this concept will help you write better code and solve real-world problems more effectively.