📦 What is an array?

An array is a variable that can store multiple values under one name.

⚠️ Arrays are supported in Bash, not in very old sh.


🔹 Declare an array

arr=(10 20 30 40)

✅ Example 1: Print all array elements

#!/bin/bash

arr=(10 20 30 40)

echo ${arr[@]}

✅ Example 2: Access single element

arr=(Apple Banana Mango)

echo ${arr[1]}

📌 Output:

Banana

(index starts from 0)


✅ Example 3: Find array length

arr=(10 20 30 40)

echo ${#arr[@]}

✅ Example 4: Loop through array

#!/bin/bash

colors=(Red Green Blue)

for c in ${colors[@]}
do
    echo $c
done

✅ Example 5: Add new element to array

arr=(1 2 3)
arr+=(4)

echo ${arr[@]}

✅ Example 6: Read array from user

read -a nums
echo ${nums[@]}

✅ Example 7: Array with string and numbers

data=("Linux" 10 "Unix" 20)

echo ${data[@]}

✅ Example 8: Using index explicitly

arr[0]=100
arr[1]=200

echo ${arr[1]}

✅ Example 9: Delete array element

arr=(10 20 30)
unset arr[1]

echo ${arr[@]}

✅ Example 10: One-line array example (EXAM GOLD ⭐)

arr=(A B C); echo ${arr[2]}

📝 Exam tips (important ⚠️)

  • Index starts from 0
  • ${arr[@]} โ†’ all elements
  • ${#arr[@]} โ†’ array size
  • Arrays work in bash, not pure sh

!/bin/bash

arr=(5 2 8 1 3)
n=${#arr[@]}

for ((i=0; i<n; i++))
do
for ((j=i+1; j<n; j++))
do
if [ ${arr[i]} -gt ${arr[j]} ]; then
temp=${arr[i]}
arr[i]=${arr[j]}
arr[j]=$temp
fi
done
done

echo “Sorted array:”
echo ${arr[@]}

Bubble sort Example

!/bin/bash

arr=(5 1 4 2 8)
n=${#arr[@]}

for ((i=0; i<n; i++))
do
for ((j=0; j<n-i-1; j++))
do
if [ ${arr[j]} -gt ${arr[j+1]} ]; then
temp=${arr[j]}
arr[j]=${arr[j+1]}
arr[j+1]=$temp
fi
done
done

echo “Sorted array:”
echo “${arr[@]}”

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *