Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Practical Shell Script Array Operations and Sorting Algorithms

Tech May 13 13

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

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...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Comprehensive Guide to Hive SQL Syntax and Operations

This article provides a detailed walkthrough of Hive SQL, categorizing its features and syntax for practical use. Hive SQL is segmented into the following categories: DDL Statements: Operations on...

Leave a Comment

Anonymous

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