0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use Array in Bash: Syntax, Examples, and Tips

In Bash, you create an array using array_name=(value1 value2 value3) and access elements with ${array_name[index]}. Arrays start at index 0, and you can get all elements using ${array_name[@]}.
📐

Syntax

To create an array, use parentheses with space-separated values. Access elements by their index inside curly braces with a dollar sign. Indexing starts at 0.

  • array_name=(value1 value2 value3): Defines an array with three elements.
  • ${array_name[index]}: Accesses the element at the given index.
  • ${array_name[@]}: Expands to all elements in the array.
bash
my_array=(apple banana cherry)
echo "First element: ${my_array[0]}"
echo "All elements: ${my_array[@]}"
Output
First element: apple All elements: apple banana cherry
💻

Example

This example shows how to create an array, print a single element, and loop through all elements to print them one by one.

bash
fruits=(apple banana cherry)
echo "Second fruit: ${fruits[1]}"

for fruit in "${fruits[@]}"; do
  echo "Fruit: $fruit"
done
Output
Second fruit: banana Fruit: apple Fruit: banana Fruit: cherry
⚠️

Common Pitfalls

Common mistakes include forgetting quotes around ${array[@]} in loops, which can cause word splitting issues, and using parentheses instead of square brackets for indexing.

Also, arrays must be declared with parentheses; using spaces without parentheses creates separate variables.

bash
# Wrong: missing quotes causes word splitting
fruits=(apple banana cherry)
for fruit in ${fruits[@]}; do
  echo "$fruit"
done

# Right: quotes preserve each element
for fruit in "${fruits[@]}"; do
  echo "$fruit"
done
Output
apple banana cherry apple banana cherry
📊

Quick Reference

CommandDescription
array=(val1 val2 val3)Create an array with values
${array[0]}Access first element
${array[@]}Access all elements
${#array[@]}Get number of elements
array+=(val4)Add element to array
unset array[index]Remove element at index

Key Takeaways

Create arrays with parentheses and space-separated values.
Access elements using ${array[index]}, starting at zero.
Use "${array[@]}" with quotes to safely loop over all elements.
Get array length with ${#array[@]}.
Add elements using += and remove with unset.