Bash: Arrays
Arrays are used to store multiple values in a single variable. This is useful for grouping related data.
Defining an Array
Syntax for defining an array
my_array=("apple" "banana" "cherry")To create an array, use parentheses `()` with each element separated by a space.
Using `declare` to define an array
#!/bin/bash
declare -a my_array
my_array[0]="apple"
my_array[1]="banana"
echo ${my_array[0]} # Result: apple
The declare -a command formally defines a variable as an indexed array. This is useful for scripts where you don't assign values immediately or need to ensure the variable is treated as an array.
Accessing Array Elements
Accessing a specific element
echo ${my_array[0]}Use `my_array[index]` to access a specific element, with array indexing starting at `0`.
Accessing all elements
echo ${my_array[@]}The `@` symbol expands the array to all of its elements.
Getting the length of an array
echo ${#my_array[@]}To get the number of elements in an array, use the `#` symbol before the array name.
Iterating over an array
for item in "${my_array[@]}"; do
echo "Item: $item"
doneYou can easily loop through all elements of an array. It's best practice to use double quotes to handle elements that may contain spaces.
Advanced Array Techniques
Adding and removing elements
You can dynamically add elements to a Bash array or remove them using the += and unset operators.
#!/bin/bash
# Initialize an array
my_array=("apple" "banana")
# Add an element to the end of the array
my_array+=("cherry")
echo "After adding: ${my_array[@]}" # Result: apple banana cherry
# Remove an element at a specific index
unset my_array[1]
echo "After removing: ${my_array[@]}" # Result: apple cherry
The unset command removes the element at the specified index, but it does **not** re-index the array. This can lead to gaps in the index numbers.
Serializing and deserializing an array
Bash arrays cannot directly store other arrays. The declare -p command can be used to serialize an array into a string, which can then be stored as an element in another array. The output of declare -p is a string that is valid Bash code.
#!/bin/bash
declare -a master_array
declare -a sub_array=("apple" "banana")
# Serialize the sub-array into a string and store it
# The output of `declare -p sub_array` is the string:
# `declare -a sub_array='([0]="apple" [1]="banana")'`
master_array+=( "$(declare -p sub_array)" )
# The sub-array is now stored as a string. To access it, you must "deserialize" it.
for arr_string in "${master_array[@]}"; do
# 'eval' re-creates the array from the serialized string
eval "$arr_string"
echo "First element of the sub-array: ${sub_array[0]}"
echo "Second element of the sub-array: ${sub_array[1]}"
done