mkdir lab04
cd lab04
#!/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:
"${words[@]}" → Access all elementss* → Matches words starting with 's'|| → OR conditionPutting efforts
Pays big time
Successful people work hard
Assessment is part of life
#!/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:
mapfile -t → Reads file into array// → Replace all occurrences#!/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:
% → Modulus operator!= 0 → Not divisible#!/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:
&& → Executes block if condition is truebreak → Terminates loop#!/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:
function_name() → Function definitionlocal → Limits variable scope$# → Argument count check#!/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:
${#variable} → Length of stringq