🐧 Linux / Shell Scripting
Intermediate
How do arrays work in bash?
Answer
Bash supports indexed arrays and associative arrays (bash 4+). Declare an indexed array: arr=("apple" "banana" "cherry") or arr[0]="apple". Access elements: ${arr[0]}. Get all elements: ${arr[@]}. Get length: ${#arr[@]}. Iterate: for item in "${arr[@]}"; do echo "$item"; done. Append: arr+=("date"). Associative arrays (declare first): declare -A map; map["key"]="value"; echo "${map["key"]}". Always quote array expansions with "${arr[@]}" to preserve elements with spaces. Arrays in bash are essential for collecting command output: files=($(find . -name "*.log")) — though mapfile/readarray is safer for filenames with spaces.
Previous
How does trap work for signal handling in bash?
Next
How does xargs work for building command lines?