System Scripting Lab 04

Arrays, Control Flow, Functions

Setup

mkdir lab04
cd lab04

Exercise 1: Array Filtering

#!/bin/bash

# Define array
words=("watch" "sweet" "zebra" "want" "switch" "script" "honey" "manager" "money" "maker" "home")

# Loop through array
for word in "${words[@]}"
do
    # Check if word starts with 's' or 'm'
    if [[ $word == s* || $word == m* ]]; then
        echo "$word"
    fi
done

Explanation:

Exercise 2: File to Array + Replace Words

content.txt

Putting efforts
Pays big time
Successful people work hard
Assessment is part of life

Script

#!/bin/bash

# Read file into array
mapfile -t lines < content.txt

# Loop through array
for line in "${lines[@]}"
do
    # Replace words
    line=${line//Successful/Distinction}
    line=${line//Assessment/Exam}

    # Output modified line
    echo "$line"
done

Explanation:

Exercise 3: Loop with Condition

#!/bin/bash

count=0

# Loop from 1 to 50
for i in {1..50}
do
    # Skip multiples of 4
    if (( i % 4 != 0 )); then
        echo "$i"
        ((count++))
    fi
done

# Output total count
echo "Numbers printed: $count"

Explanation:

Exercise 4: Divisible by 7 (No IF)

#!/bin/bash

while true
do
    read -p "Enter a number: " num

    # Use modulo directly in loop condition
    (( num % 7 == 0 )) && {
        echo "Success! Number divisible by 7."
        break
    }

    echo "Try again..."
done

Explanation:

Exercise 5: Function with Arithmetic Logic

#!/bin/bash

# Check arguments
if [ $# -ne 2 ]; then
    echo "Usage: $0 num1 num2"
    exit 1
fi

# Function definition
calculate() {
    local a=$1
    local b=$2

    # Check if first number is odd
    if (( a % 2 != 0 )); then
        echo "Addition result: $((a + b))"
    else
        echo "Multiplication result: $((a * b))"
    fi
}

# Call function
calculate $1 $2

Explanation:

Exercise 6: Character Count Function

#!/bin/bash

# Function to count characters
count_chars() {
    local input="$1"
    echo "Character count: ${#input}"
}

while true
do
    read -p "Enter text (q to quit): " text

    # Exit condition
    if [ "$text" == "q" ]; then
        echo "Bye!"
        break
    fi

    # Call function
    count_chars "$text"
done

Explanation:

Key Exam Tips