Indexed Arrays in Bash
Bash supports one-dimensional arrays where elements are accessed via zero-based integer indices. Unlike strictly typed languages, Bash arrays are dynamic and can hold mixed data types without explicit declaration.
Defining and Initializing
Arrays are defined using parentheses () with elements separated by whitespace. The assignment operator = must not have surrounding spaces.
my_hosts=(webserver dbserver mailserver)
# Accessing elements
echo "First element: ${my_hosts[0]}"
# Accessing all elements
echo "All items: ${my_hosts[*]}"
Sparse Arrays
You are not required to populate indices sequentially. You can assign values to specific indices, creating a sparse array structure.
log_levels=([0]="EMERG" [3]="ERROR" [7]="DEBUG")
echo "Index 3: ${log_levels[3]}" # Outputs: ERROR
Array Operations
Calculating Length
Use the # operator preceding the array reference to get the count of elements.
tools=(hammer wrench screwdriver)
echo "Total tools: ${#tools[@]}"
# String length of an element
long_string=" Supercalifragilisticexpialidocious "
echo "String length: ${#long_string}"
Array Concatenation
Merging two arrays involves expanding both collections and wrapping them in new parentheses.
alpha=(a b c)
numeric=(1 2 3)
combined=(${alpha[@]} ${numeric[*]})
echo ${combined[@]} # Output: a b c 1 2 3
Deleting Elements and Arrays
The unset builtin removes specific indices or the entire variable. Note that unsetting an index does not re-index the array; it leaves a gap.
files=(file1 file2 file3 file4)
unset files[1] # Removes 'file2'
echo "Remaining: ${files[@]}" # Output: file1 file3 file4
unset files # Deletes the array entirely
Associative Arrays
Associative arrays function like dictionaries or hash maps, using string keys instead of integers. They must be explicitly declared using declare -A.
Declaration and Assignment
You can populate the array during declaration or assign values incrementally.
declare -A server_config
# Incremental assignment
server_config["host"]="192.168.1.10"
server_config["port"]="8080"
# Bulk assignment
declare -A user_roles=( [admin]="full_access" [guest]="read_only" )
Accessing Keys and Values
To manipulate associative arrays, you need to distinguish between keys and values using the ! prefix for keys.
declare -A app_state=( [status]="running" [cpu]="45%" [mem]="2048MB" )
# Get all values
echo "Values: ${app_state[@]}"
# Get all keys
echo "Keys: ${!app_state[@]}"
# Get specific value
echo "Memory usage: ${app_state[mem]}"
Iterating Over Associative Arrays
Looping through keys allows you to access both the key and its corresponding value.
declare -A site_meta=( [title]="Tech Blog" [visitors]=1500 [ssl]="enabled" )
for key in "${!site_meta[@]}"; do
echo "Key: $key, Value: ${site_meta[$key]}"
done
Data Transformation
Bash makes it easy to convert between strings and arrays. When a string is unquoted inside parentheses, word splitting occurs, creating an array.
csv_data="red,green,blue"
IFS=',' read -r -a color_array <<< "$csv_data"
echo "Array count: ${#color_array[@]}"
echo "Second color: ${color_array[1]}"