Arrays are a powerful feature in Bash that allow you to store multiple values in a single variable. They can be used for various complex operations, such as processing lists of items, performing batch operations, and more. In this tutorial, we will explore how to declare, manipulate, and use arrays in Bash scripts.
In Bash, an array is essentially a list of strings, where each string is an element of the array. Arrays can be indexed starting from 0, similar to many other programming languages. You can access individual elements using their index or iterate over all elements in the array.
You can declare arrays in several ways:
Using parentheses:
fruits=("apple" "banana" "cherry")
Using square brackets:
fruits=(["0"]="apple" ["1"]="banana" ["2"]="cherry")
Appending elements:
fruits=()
fruits+=("apple")
fruits+=("banana")
fruits+=("cherry")
You can access individual elements of an array using their index:
echo ${fruits[0]} # Output: apple
To access all elements, you can use the @ or * symbol:
echo ${fruits[@]} # Output: apple banana cherry
echo ${fruits[*]} # Output: apple banana cherry
You can find the length of an array using the ${#array[@]} syntax:
echo ${#fruits[@]} # Output: 3
Let's explore some practical examples to understand how arrays work in Bash.
#!/bin/bash
# Declare an array
fruits=("apple" "banana" "cherry")
# Print all elements
echo "All fruits: ${fruits[@]}"
# Add a new fruit
fruits+=("date")
echo "After adding date: ${fruits[@]}"
# Remove the first element
unset fruits[0]
echo "After removing apple: ${fruits[@]}"
All fruits: apple banana cherry After adding date: apple banana cherry date After removing apple: banana cherry date
You can use a for loop to iterate over all elements in an array:
#!/bin/bash
# Declare an array
fruits=("apple" "banana" "cherry")
# Iterate over the array
for fruit in "${fruits[@]}"; do
echo "I like $fruit"
done
I like apple I like banana I like cherry
While not covered in this section, Bash also supports associative arrays, which allow you to use strings as indices. You can learn more about them in the "Bash Associative Arrays" section.
In the next tutorial, we will explore Bash Associative Arrays, which provide a way to map keys to values similar to dictionaries or hash maps in other programming languages. This feature is particularly useful for more complex data structures and operations.
Stay tuned for more advanced topics in Bash scripting!