Arrays in Bash
Bash provides both indexed and associative arrays for storing collections of data. Arrays are powerful tools for managing lists of items in scripts.
Indexed Arrays
Indexed arrays are the most common type, with numerically indexed elements:
# Declare an indexed array
declare -a colors=("red" "green" "blue")
# Alternative syntax
colors=("red" "green" "blue")
# Add elements
colors+=("yellow" "orange")
# Access elements
echo ${colors[0]} # red
echo ${colors[@]} # all elements
echo ${#colors[@]} # number of elements
Associative Arrays
Associative arrays (Bash 4+) use strings as keys:
# Declare an associative array
declare -A user=([name]="Alice" [age]=30 [email]="alice@example.com")
# Access elements
echo ${user[name]} # Alice
echo ${user[email]} # alice@example.com
# List all keys
echo ${!user[@]}
# List all values
echo ${user[@]}
Array Operations
# Iterate through array elements
for color in "${colors[@]}"; do
echo "Color: $color"
done
# Iterate with index
for i in "${!colors[@]}"; do
echo "Color $i: ${colors[$i]}"
done
# Slice an array
echo "${colors[@]:1:2}" # elements from index 1, length 2
# Remove an element
unset colors[1]
# Remove entire array
unset colors
Reading Files into Arrays
# Read lines of a file into an array
mapfile -t lines < file.txt
# Process each line
for line in "${lines[@]}"; do
echo "Line: $line"
done
# Alternative method
IFS=$'\n' read -d '' -ra lines < file.txt
Command Output to Array
# Store command output in array
files=($(ls *.txt))
# Safer version (handles spaces in filenames)
IFS=$'\n' read -d '' -ra files < <(find . -name "*.txt" -print0)
Multidimensional Arrays
Bash doesn't directly support multidimensional arrays, but you can simulate them:
declare -A matrix
matrix[0,0]=1
matrix[0,1]=2
matrix[1,0]=3
matrix[1,1]=4
echo "${matrix[0,1]}" # 2
Array Manipulation Functions
# Function to check if array contains value
contains() {
local array="$1[@]"
local seeking=$2
local in=1
for element in "${!array}"; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
# Usage
if contains colors "red"; then
echo "Red is in the array"
fi
Best Practices
- Always quote array expansions:
"${array[@]}"
- Use
declare -a
for indexed arrays anddeclare -A
for associative arrays - For associative arrays, check Bash version (requires Bash 4+)
- Be careful with word splitting when creating arrays from command output
- Consider using
mapfile
for reading files into arrays
Practical Examples
# Process command line arguments
args=("$@")
for arg in "${args[@]}"; do
case $arg in
-v) verbose=1 ;;
-d) debug=1 ;;
esac
done
# Configuration as associative array
declare -A config=(
[host]="example.com"
[port]=8080
[user]="admin"
)
echo "Connecting to ${config[host]}:${config[port]}"
# Matrix multiplication (simulated)
declare -A mat1=([0,0]=1 [0,1]=2 [1,0]=3 [1,1]=4)
declare -A mat2=([0,0]=5 [0,1]=6 [1,0]=7 [1,1]=8)
declare -A result
for i in 0 1; do
for j in 0 1; do
result[$i,$j]=$(( mat1[$i,0] * mat2[0,$j] + mat1[$i,1] * mat2[1,$j] ))
done
done
echo "Result matrix:"
echo "${result[0,0]} ${result[0,1]}"
echo "${result[1,0]} ${result[1,1]}"
Next: Debugging & Error Handling