Calculating Mathematical Expressions in Shell Scripting – Part 5

By now, you must be feeling a bit more confident writing and understanding basic shell scripts. If you’ve followed the previous parts of this tutorial series, you’re already familiar with variables, loops, conditions, and simple operations in shell scripting.

This is the fifth part of this shell scripting tutorial series. In this post, we’ll explore slightly advanced mathematical operations and how to handle them using shell scripts.

Let’s Start with the Fibonacci Series

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones. It starts with 0 and 1, so the series goes: 0, 1, 1, 2, 3, 5, 8, and so on.

Script 1: Fibonacci.sh

#!/bin/bash

echo "How many numbers of the Fibonacci series do you want?" 
read total 

# Initialize the first two numbers
x=0 
y=1 

echo "Fibonacci Series up to $total terms:"

# Print the first two numbers
echo "$x" 
echo "$y" 

# Loop starts from the 3rd term
i=2 
while [ $i -lt $total ] 
do 
    z=$((x + y))  # Next number is sum of previous two
    echo "$z" 
    x=$y 
    y=$z 
    i=$((i + 1)) 
done
Calculating Fibonacci Numbers
Calculating Fibonacci Numbers

Decimal to Binary Conversion

Every computer understands binary: only 0s and 1s. Here’s how you can write a shell script to convert a Decimal number (like 10) to Binary (1010).

Script 2: Decimal2Binary.sh

#!/bin/bash

# Create an array of powers of 2 (2^31 to 2^0)
for ((i=32;i>=0;i--)); do 
    power=$((2**i)) 
    powersOfTwo+=( $power ) 
done 

# Check if input was provided
if [ $# -eq 0 ]; then
    echo -e "Usage: ./Decimal2Binary.sh <number1> <number2> ..."
    exit 1
fi

echo -e "Decimal\t\tBinary"

# Convert each number to binary
for num in "$@"; do 
    binary=""
    started=0

    for pow in "${powersOfTwo[@]}"; do
        if [ $num -lt $pow ]; then
            if [ $started -eq 1 ]; then
                binary+="0"
            fi
        else
            binary+="1"
            num=$((num - pow))
            started=1
        fi
    done

    echo -e "$1\t\t$binary"
done
Convert Decimal Number to Binary
Convert Decimal Number to Binary

Want a quicker way? use the bc command, which will convert a decimal number to binary in a single line of code.

echo "obase=2; NUM" | bc

Replace NUM with the decimal number you want to convert to binary.

echo "obase=2; 121" | bc

This will output the binary equivalent of 121, which is 1111001.

Binary to Decimal Conversion

Next, we will write a script that performs the opposite of the above script, converting binary values to decimal.

Script 3: Binary2Decimal.sh

#!/bin/bash

echo "Enter a binary number:"
read Binary

# Check if input is a valid binary number
if ! [[ $Binary =~ ^[01]+$ ]]; then
    echo "Please enter a valid binary number (only 0 and 1 allowed)."
    exit 1
fi

Decimal=0
power=1

# Loop from right to left
while [ $Binary -ne 0 ]; do
    digit=$((Binary % 10))
    Decimal=$((Decimal + digit * power))
    power=$((power * 2))
    Binary=$((Binary / 10))
done

echo "Decimal Value: $Decimal"
Convert Binary to Decimal
Convert Binary to Decimal

The above conversion can be performed directly in the terminal using the bc command as follows:

echo "ibase=2; BINARY" | bc

Simply replace BINARY with the binary number you want to convert.

echo "ibase=2; 11010101" | bc

This will output the corresponding decimal value.

Other Number Base Conversions Using bc Command

Similarly, you can write scripts to convert between octal, hexadecimal, and decimal, both ways. You can also accomplish these conversions directly in the terminal using the bc command.

Decimal to Octal

echo "obase=8; 123" | bc

Decimal to Hexadecimal

echo "obase=16; 123" | bc

Octal to Decimal

echo "ibase=8; 173" | bc

Hexadecimal to Decimal

echo "ibase=16; 7B" | bc

Binary to Octal

echo "ibase=2; obase=8; 101101" | bc

Common Numeric Tests in Shell Scripting

Use these tests inside if statements to compare numbers.

Test Command Meaning
[ $a -eq $b ] a is equal to b
[ $a -ne $b ] a is not equal to b
[ $a -gt $b ] a is greater than b
[ $a -lt $b ] a is less than b
[ $a -ge $b ] a is greater than or equal to b
[ $a -le $b ] a is less than or equal to b
Conclusion

In this fifth part of our shell scripting tutorial series, we’ve ventured into slightly more advanced mathematical operations, focusing on converting numbers between different bases and calculating the Fibonacci series.

By now, you should feel more confident in handling basic mathematical operations in shell scripts, like generating the Fibonacci sequence and performing conversions between decimal, binary, octal, and hexadecimal number systems.

Ravi Saive
I am an experienced GNU/Linux expert and a full-stack software developer with over a decade in the field of Linux and Open Source technologies

Each tutorial at TecMint is created by a team of experienced Linux system administrators so that it meets our high-quality standards.

Join the TecMint Weekly Newsletter (More Than 156,129 Linux Enthusiasts Have Subscribed)
Was this article helpful? Please add a comment or buy me a coffee to show your appreciation.

2 Comments

Leave a Reply

Got Something to Say? Join the Discussion...

Thank you for taking the time to share your thoughts with us. We appreciate your decision to leave a comment and value your contribution to the discussion. It's important to note that we moderate all comments in accordance with our comment policy to ensure a respectful and constructive conversation.

Rest assured that your email address will remain private and will not be published or shared with anyone. We prioritize the privacy and security of our users.