tldr

What Are Arrays in Bash Scripts and How Do I Use Them?

Bash Arrays

Arrays are a fundamental component in bash scripting, offering a powerful way to manage collections of data. They simplify the processing of large datasets and enhance script efficiency. In this article, we will explore what arrays are in bash scripts, how to utilize them effectively, and best practices for their use.

What Are Arrays in Bash Scripts?

In bash scripting, an array is a data structure that can store multiple values under a single variable name. Arrays allow you to organize and manage data systematically, making it easier to perform batch operations and streamline workflows.

Types of Arrays

  • Indexed Arrays: These are the most common type of arrays where each element is identified by a numeric index.
  • Associative Arrays: These arrays use named keys instead of numeric indices, introduced in Bash version 4.

How to Declare and Initialize Arrays

Indexed Arrays

To declare an indexed array, you can use the following syntax:

declare -a array_name

To initialize an array with elements:

fruits=("apple" "banana" "cherry")

Associative Arrays

Associative arrays require an explicit declaration:

declare -A animal_sounds

To assign values:

animal_sounds=([dog]="bark" [cat]="meow" [cow]="moo")

Accessing Array Elements

Accessing elements in arrays is straightforward:

For indexed arrays:

echo ${fruits[1]} # Outputs 'banana'

For associative arrays:

echo ${animal_sounds[cat]} # Outputs 'meow'

Looping Through Arrays

Looping through arrays can be accomplished using loops, such as for:

Indexed Arrays

for fruit in "${fruits[@]}"; do
    echo $fruit
done

Associative Arrays

for animal in "${!animal_sounds[@]}"; do
    echo "$animal makes a ${animal_sounds[$animal]} sound."
done

Modifying Arrays

You can modify and manage arrays dynamically:

Adding Elements

fruits+=("orange")

Removing Elements

To remove a specific element, unset it:

unset fruits[1]

Best Practices for Using Arrays

  1. Keep Track of Array Indexes: Always be cautious when handling indices, especially in loops and conditional checks.
  2. Version Check for Associative Arrays: Ensure your bash version supports associative arrays.
  3. Efficient Looping: Use ${!array[@]} for associative arrays to loop through keys effectively.

Learn More About Bash Scripting

Expand your knowledge on bash scripting tutorials and explore advanced concepts like bash file processing and running projects with a bash file.


Harness the power of arrays in bash scripts to write more efficient and cleaner code. Whether you are managing server configurations or processing data sets, arrays are invaluable tools in your scripting arsenal.