Shell scripts become fragile when a list is stored as one space-separated string, because filenames, labels, or host names that contain spaces can turn into extra arguments. Bash arrays keep each value as a separate element so a script can loop, count, remove, and pass the values without guessing where one item ends.
Indexed arrays use numeric positions starting at zero. They work well for ordered values such as log files, service names, or command arguments, and quoted [@] expansion keeps each element separate when the loop or command receives the values.
Associative arrays use named keys and require Bash 4 or newer. The script below combines an ordered file list with a keyed owner map, then verifies the first element, full list, element count, key lookup, quoted loop behavior, and remaining values after one indexed element is removed.
Related: How to use variables in Bash scripts
Related: How to use parameter expansion in Bash
Related: How to loop over files in Bash
#!/usr/bin/env bash set -euo pipefail files=("app.log" "db backup.log") files+=("web.log") declare -A owners=( [app]="alice" [db]="maria" ) printf "first file: %s\n" "${files[0]}" printf "all files: %s\n" "${files[*]}" printf "file count: %s\n" "${#files[@]}" printf "db owner: %s\n" "${owners[db]}" for file in "${files[@]}"; do printf "check <%s>\n" "$file" done unset 'files[1]' printf "remaining files: %s\n" "${files[*]}"
Use an indexed array for ordered values and an associative array when a descriptive key such as db or app makes the lookup clearer.
$ bash -n array-demo.sh
No output means Bash did not find a parse error.
$ bash array-demo.sh first file: app.log all files: app.log db backup.log web.log file count: 3 db owner: maria check <app.log> check <db backup.log> check <web.log> remaining files: app.log web.log
for file in "${files[@]}"; do
printf "check <%s>\n" "$file"
done
Unquoted array expansion can split elements that contain spaces and change how many arguments the command receives.
unset 'files[1]'
Quoting prevents pathname expansion from treating brackets as a shell pattern before unset receives the array subscript.
printf "file count: %s\n" "${#files[@]}"