bash arrays — create, iterate, append, slice
Quick Answer
# Declare an array
fruits=("apple" "banana" "cherry")
# Access elements
echo "${fruits[0]}" # apple
echo "${fruits[@]}" # all elements
echo "${#fruits[@]}" # length: 3
# Iterate
for item in "${fruits[@]}"; do
echo "$item"
done
Usage
Arrays let you store lists of values and iterate over them in bash scripts.
Other causes & fixes
Append and remove elements
# Append
fruits+=("date")
# Remove element at index 1
unset 'fruits[1]'
# Re-index after removal (gaps exist otherwise)
fruits=("${fruits[@]}")
Slice and subarray
# Elements from index 1, length 2
echo "${fruits[@]:1:2}" # banana cherry
# Last element
echo "${fruits[-1]}"
Array from command output
# Split by newline
mapfile -t files < <(find . -name "*.txt")
echo "${#files[@]} files found"
# Split by space (word splitting)
words=($( echo "one two three" ))
Associative arrays (bash 4+)
declare -A config
config["host"]="localhost"
config["port"]="5432"
echo "${config["host"]}"
for key in "${!config[@]}"; do
echo "$key=${config[$key]}"
done
Related