Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Practical Shell Script Array Operations and Sorting Algorithms

Tech May 13 2

1. Implementing Bubble Sort with Arrays and Loops

Bubble sort compares adjacent elements and swaps them if they are in the wrong order. The algorithm requires nested loops: an outer loop for the number of passes, and an inner loop for comparisons within each pass.

#!/bin/bash
# Initialize the dataset
numbers=(4 5 2 1 3 0)

# Outer loop: number of passes
for ((pass=0; pass<${#numbers[@]}-1; pass++))
do
    # Inner loop: compare adjacent elements
    for ((idx=0; idx<${#numbers[@]}-1-pass; idx++))
    do
        # Swap if current element is greater than next
        if [ ${numbers[idx]} -gt ${numbers[idx+1]} ]; then
            tmp=${numbers[idx]}
            numbers[idx]=${numbers[idx+1]}
            numbers[idx+1]=$tmp
        fi
    done
    echo "After pass $((pass+1)): ${numbers[@]}"
done

2. Refactoring Bubble Sort into Modular Functions

The sorting logic can be separated into two functions: one handles the comparison and swapping of adjacent elements, while the other manages the iteration passes.

#!/bin/bash

compare_and_swap() {
    for ((idx=0; idx<${#dataset[@]}-1-pass; idx++))
    do
        if [ ${dataset[idx]} -gt ${dataset[idx+1]} ]; then
            tmp=${dataset[idx]}
            dataset[idx]=${dataset[idx+1]}
            dataset[idx+1]=$tmp
        fi
    done
}

run_sort_passes() {
    for ((pass=0; pass<${#dataset[@]}-1; pass++))
    do
        compare_and_swap
    done
    echo "${dataset[@]}"
}

dataset=(5 2 8 1 9)
run_sort_passes

Accepting array input as a parameter allows for greater flexibility:

#!/bin/bash

compare_and_swap() {
    for ((idx=0; idx<${#dataset[@]}-1-pass; idx++))
    do
        if [ ${dataset[idx]} -gt ${dataset[idx+1]} ]; then
            tmp=${dataset[idx]}
            dataset[idx]=${dataset[idx+1]}
            dataset[idx+1]=$tmp
        fi
    done
}

run_sort_passes() {
    for ((pass=0; pass<${#dataset[@]}-1; pass++))
    do
        compare_and_swap
    done
    echo "${dataset[@]}"
}

dataset=($1)
run_sort_passes

3. Incrementing Each Element in an Integer Array

When processing numeric arrays, arithmetic operations can be applied to each element through iteration. The following example increments each value by 10 using arithmetic expansion.

#!/bin/bash
# Define an integer array
values=(5 2 7 1 3)

# Process each element
for ((i=0; i<${#values[@]}; i++))
do
    # Add 10 to each value
    values[i]=$((values[i] + 10))
done

echo "Modified array: ${values[@]}"

4. Sorting Disk Usage Percentages

System administrators often need to analyze disk usage. This example extracts the usage percentages from the df command and sorts them in ascending order.

#!/bin/bash

# Extract disk usage percentages, removing the header and percent signs
usage_data=$(df -h | awk 'NR>1 {print $5}' | tr -d '%')
dataset=($usage_data)

compare_and_swap() {
    for ((idx=0; idx<${#dataset[@]}-1-pass; idx++))
    do
        if [ ${dataset[idx]} -gt ${dataset[idx+1]} ]; then
            tmp=${dataset[idx]}
            dataset[idx]=${dataset[idx+1]}
            dataset[idx+1]=$tmp
        fi
    done
}

run_sort_passes() {
    for ((pass=0; pass<${#dataset[@]}-1; pass++))
    do
        compare_and_swap
    done
    echo "${dataset[@]}"
}

run_sort_passes

5. Sorting Files by Size in Current Directory

File sizes can be extracted using ls and awk, then sorted numerically to identify the largest or smallest files in a directory.

#!/bin/bash

# Extract file sizes from current directory, skipping the header
file_sizes=$(ls -l | awk 'NR>1 {print $5}')
dataset=($file_sizes)

compare_and_swap() {
    for ((idx=0; idx<${#dataset[@]}-1-pass; idx++))
    do
        if [ ${dataset[idx]} -gt ${dataset[idx+1]} ]; then
            tmp=${dataset[idx]}
            dataset[idx]=${dataset[idx+1]}
            dataset[idx+1]=$tmp
        fi
    done
}

run_sort_passes() {
    for ((pass=0; pass<${#dataset[@]}-1; pass++))
    do
        compare_and_swap
    done
    echo "${dataset[@]}"
}

run_sort_passes

An alternative approach passes the file size data directly as a command argument:

bash sort_script.sh "$(ls -l | awk 'NR>1 {print $5}' | tr '\n' ' ')"

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.