array, aictionary, for and while loops to score 25 marks in System Commands OPPE

abbazs - Aug 23 - - Dev Community

Introduction

This guide covers concepts focusing on arrays, loops, file operations, arithmetic operations, and string manipulation.

1. Arrays in Bash

Arrays in Bash are zero-indexed lists of values. There are several ways to declare and initialize arrays.

Declaring and Initializing Arrays

  1. Using declare:
declare -a my_array
Enter fullscreen mode Exit fullscreen mode
  1. Implicit declaration with initialization:
my_array=(apple banana cherry)
Enter fullscreen mode Exit fullscreen mode
  1. Empty array declaration:
my_array=()
Enter fullscreen mode Exit fullscreen mode
  1. Declaring with specific indices:
my_array=([0]="apple" [1]="banana" [5]="cherry")
Enter fullscreen mode Exit fullscreen mode
  1. Declaring empty and adding elements:
my_array=()
my_array+=("apple")
my_array+=("banana")
Enter fullscreen mode Exit fullscreen mode
  1. Declaring a read-only array:
declare -ar my_readonly_array=(apple banana cherry)
Enter fullscreen mode Exit fullscreen mode

Accessing and Manipulating Arrays

# Access elements
echo ${my_array[0]}  # Output: apple

# Get all elements
echo ${my_array[@]}  # Output: apple banana cherry

# Get array length
echo ${#my_array[@]}  # Output: 3

# Slicing an array
echo ${my_array[@]:1:2}  # Output: banana cherry (from index 1, take 2 elements)

# Finding the indices of an array
echo ${!my_array[@]}  # Output: 0 1 2 (or 0 1 5 for the array with specific indices)
Enter fullscreen mode Exit fullscreen mode

2. Loops in Bash

Bash provides several types of loops for repetitive tasks.

For Loops

  1. Traditional for loop:
for i in 1 2 3 4 5
do
    echo $i
done
Enter fullscreen mode Exit fullscreen mode
  1. C-style for loop:
for ((i=0; i<5; i++))
do
    echo $i
done
Enter fullscreen mode Exit fullscreen mode
  1. For loop with array:
fruits=(apple banana cherry)
for fruit in "${fruits[@]}"
do
    echo $fruit
done
Enter fullscreen mode Exit fullscreen mode
  1. For loop with command substitution:
for file in $(ls)
do
    echo $file
done
Enter fullscreen mode Exit fullscreen mode

While Loops

Basic while loop syntax:

count=1
while [ $count -le 5 ]
do
    echo "Count is: $count"
    ((count++))
done
Enter fullscreen mode Exit fullscreen mode

3. File Operations

Reading from and writing to files is a common task in Bash scripting.

Reading a File Line by Line

while IFS= read -r line
do
    echo "Line: $line"
done < "input.txt"
Enter fullscreen mode Exit fullscreen mode

Writing to a File

echo "Hello, World!" > output.txt
echo "Appending this line" >> output.txt
Enter fullscreen mode Exit fullscreen mode

4. Arithmetic Operations in Bash

Bash offers various methods for arithmetic operations:

# Using let
let result=5+3
echo $result  # Output: 8

# Using (( ))
((result = 5 + 3))
echo $result  # Output: 8

# Using $[ ]
result=$[5 + 3]
echo $result  # Output: 8

# Using expr (note the spaces)
result=$(expr 5 + 3)
echo $result  # Output: 8
Enter fullscreen mode Exit fullscreen mode

5. String Manipulation

String Case Checking

This example checks if given strings start with uppercase or lowercase letters:

#!/bin/bash

declare -a upper
declare -a lower

words=("Hello" "world" "BASH" "script" "ARRAY" "example")

for word in "${words[@]}"
do
    if [[ $word == [[:upper:]]* ]]
    then
        upper+=("$word")
    elif [[ $word == [[:lower:]]* ]]
    then
        lower+=("$word")
    fi
done

echo "Uppercase words: ${upper[@]}"
echo "Lowercase words: ${lower[@]}"
Enter fullscreen mode Exit fullscreen mode

Advanced Pattern Matching

This script demonstrates number detection and pattern matching:

#!/bin/bash

declare -a num_var
declare -a userid_var
declare -a other_var

strings=("123" "abc" "456" "1234abcd56" "789xyz" "2023user01" "hello123")

for str in "${strings[@]}"
do
    if [[ $str =~ ^[0-9]+$ ]]
    then
        # String is a number
        num_var+=("$str")
    elif [[ $str =~ ^[0-9]{4}[a-z]{4}[0-9]{2}$ ]]
    then
        # String matches pattern \d{4}[a-z]{4}\d{2}
        userid_var+=("$str")
    else
        # String doesn't match any specific category
        other_var+=("$str")
    fi
done

echo "Numbers: ${num_var[@]}"
echo "User IDs: ${userid_var[@]}"
echo "Other strings: ${other_var[@]}"
Enter fullscreen mode Exit fullscreen mode

6. Comprehensive Example: File Processing and Data Categorization

This example combines file reading, loops, and string manipulation to categorize data from a file:

#!/bin/bash

# Initialize arrays for different types of data
declare -a names
declare -a numbers
declare -a emails
declare -a mixed

# Read the file line by line
while IFS= read -r line
do
    # Check if line is a name (contains only letters and spaces)
    if [[ $line =~ ^[[:alpha:][:space:]]+$ ]]
    then
        names+=("$line")
    # Check if line is a number
    elif [[ $line =~ ^[0-9]+$ ]]
    then
        numbers+=("$line")
    # Check if line is an email
    elif [[ $line =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}$ ]]
    then
        emails+=("$line")
    # If it doesn't match any of the above, it's mixed content
    else
        mixed+=("$line")
    fi
done < "data.txt"

# Print the categorized data
echo "Names: ${names[@]}"
echo "Numbers: ${numbers[@]}"
echo "Emails: ${emails[@]}"
echo "Mixed Content: ${mixed[@]}"
Enter fullscreen mode Exit fullscreen mode

This script reads a file named data.txt, categorizes each line based on its content, and stores it in the appropriate array.

Conclusion

This tutorial has covered essential Bash scripting concepts including:

  1. Array declaration and manipulation
  2. For and while loops
  3. File reading and writing operations
  4. Arithmetic operations
  5. String manipulation and pattern matching
  6. A comprehensive example combining multiple concepts
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player