USD ($)
$
United States Dollar
Euro Member Countries
India Rupee
د.إ
United Arab Emirates dirham
ر.س
Saudi Arabia Riyal

Arrays and Data Structures

Lesson 4/40 | Study Time: 20 Min

Arrays are powerful data structures in Linux shell scripting that allow you to store and manage multiple values within a single variable efficiently.

Unlike simple scalar variables that hold only one value at a time, arrays organize collections of related data, making scripts more flexible and capable of handling complex tasks such as processing lists, managing configuration data, or batching commands. 

Shell scripting supports both indexed arrays—where elements are accessed by numeric indices—and associative arrays—where elements are accessed by named keys. 

Indexed Arrays

Indexed arrays use numeric indices starting at 0 by default. Elements can be assigned individually or collectively.

Declaration and Initialization:

bash
declare -a indexed_array # Explicit declaration
indexed_array=(apple banana cherry) # Compound assignment
indexed_array[3]=date # Adding an element by index


Accessing Elements:


1. Access single element: ${indexed_array[1]} outputs "banana"

2. Access all elements: ${indexed_array[@]} or ${indexed_array[*]}

3. Length of array: ${#indexed_array[@]}


Example:

bash
for element in "${indexed_array[@]}"; do
echo "Fruit: $element"
done

Associative Arrays

Introduced in Bash 4, associative arrays allow elements to be accessed by arbitrary string keys rather than numeric indices.

Declaration and Initialization:

bash
declare -A assoc_array # Declare an associative array
assoc_array=([name]="Alice" [role]="Developer" [location]="NY")
assoc_array[project]="Linux Mastery"


Accessing Elements:


1. Access by key: ${assoc_array[name]} outputs "Alice"

2. Access all keys: ${!assoc_array[@]}

3. Access all values: ${assoc_array[@]}

4. Length: ${#assoc_array[@]}


Example:

bash
for key in "${!assoc_array[@]}"; do
echo "$key: ${assoc_array[$key]}"
done


Array Manipulation Techniques


1. Adding Elements: Assign directly by index or key.

2. Updating Elements: Overwrite by reassigning values at indices or keys.

3. Deleting Elements: Use unset command (unset indexed_array[2], unset assoc_array[key])

4. Slicing Arrays: Extract parts of arrays using ${array[@]:start:length} syntax.

5. Searching: Using loops or utilities like grep on array contents.

6. Length Measurement: ${#array[@]} counts number of elements.

Iteration Patterns

Looping through arrays is essential for processing each element efficiently.

For Loop:

bash
for element in "${indexed_array[@]}"; do
echo $element
done


Index-based Loop:

bash
for (( i=0; i<${#indexed_array[@]}; i++ )); do
echo "Index $i: ${indexed_array[i]}"
done


Associative Array Loop:

bash
for key in "${!assoc_array[@]}"; do
echo "$key: ${assoc_array[$key]}"
done