Arrays
Working with arrays in Bash
Basic array operations
Basic array declaration, access, and manipulation
#!/bin/bash
# Declare array
fruits=("apple" "banana" "cherry")
# Access elements
echo "First fruit: ${fruits[0]}"
echo "All fruits: ${fruits[@]}"
echo "Array length: ${#fruits[@]}"
# Add element
fruits+=("orange")
echo "After adding: ${fruits[@]}"
Array iteration methods
Different methods to iterate through arrays
#!/bin/bash
colors=("red" "green" "blue" "yellow")
# Method 1: Index-based iteration
for (( i=0; i<${#colors[@]}; i++ )); do
echo "Color $i: ${colors[$i]}"
done
# Method 2: Direct iteration
for color in "${colors[@]}"; do
echo "Color: $color"
done
Associative arrays
Working with associative arrays (key-value pairs)
#!/bin/bash
# Declare associative array
declare -A person
person["name"]="John"
person["age"]="30"
person["city"]="New York"
# Access values
echo "Name: ${person["name"]}"
echo "Age: ${person["age"]}"
# Iterate through associative array
for key in "${!person[@]}"; do
echo "$key: ${person[$key]}"
done