Problem Statement
How do you declare and access array elements in bash?
Explanation
Array declaration: ARRAY=(val1 val2 val3) or ARRAY[0]=val1; ARRAY[1]=val2. Access elements: ${ARRAY[0]} (first element), ${ARRAY[1]} (second), etc. Indices are 0-based. Without index, ${ARRAY} returns first element. All elements: "${ARRAY[@]}" expands to separate words, "${ARRAY[*]}" expands to single word.
Array length: ${#ARRAY[@]} returns number of elements, ${#ARRAY[0]} returns length of first element. Append: ARRAY+=(new_element). Slice: ${ARRAY[@]:start:length} extracts elements. Example: ${ARRAY[@]:1:2} gets 2 elements starting at index 1. Unset element: unset ARRAY[2] removes element at index 2.
Iterate array: for item in "${ARRAY[@]}"; do echo "$item"; done. With indices: for i in "${!ARRAY[@]}"; do echo "$i: ${ARRAY[$i]}"; done. Read into array: readarray -t ARRAY < file.txt or mapfile -t ARRAY < file.txt loads file lines into array.
Associative arrays (bash 4+): declare -A ASSOC creates associative array (key-value pairs). Access: ASSOC[key]=value, ${ASSOC[key]}. Keys: ${!ASSOC[@]}. Example:
```bash
declare -A CONFIG
CONFIG[host]="localhost"
CONFIG[port]=8080
echo ${CONFIG[host]}
```
Understanding arrays enables handling multiple values, processing lists, and building complex data structures in scripts.
