Bash arrays are versatile data structures that allow you to store multiple values under a single variable name. They provide a convenient way to organize and manipulate collections of data in shell scripts.
In Bash, you can declare an array using parentheses. Here's a simple example:
fruits=(apple banana orange)
This creates an array named fruits
with three elements. You can also declare arrays on separate lines:
colors=(
red
green
blue
)
To access individual elements of an array, use square brackets with the index number. Remember, Bash arrays are zero-indexed:
echo ${fruits[0]} # Outputs: apple
echo ${colors[2]} # Outputs: blue
To print all elements of an array, use the @
or *
symbol:
echo ${fruits[@]} # Outputs: apple banana orange
You can append elements to an array using the +=
operator:
fruits+=(grape)
echo ${fruits[@]} # Outputs: apple banana orange grape
To remove an element, use the unset
command:
unset fruits[1]
echo ${fruits[@]} # Outputs: apple orange grape
To get the number of elements in an array, use the #
symbol:
echo ${#fruits[@]} # Outputs: 3
You can use a Bash For Loop to iterate over array elements:
for fruit in "${fruits[@]}"
do
echo "I like $fruit"
done
Bash 4.0 and later versions support associative arrays, which use string keys instead of numeric indices:
declare -A user_info
user_info[name]="John"
user_info[age]=30
echo ${user_info[name]} # Outputs: John
Arrays in Bash provide a robust way to handle collections of data. They're particularly useful for processing lists of files, managing configuration options, or storing command-line arguments. By mastering arrays, you'll significantly enhance your shell scripting capabilities.