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.

Steps to use arrays in Bash:

  1. Create a script that stores an ordered list and a keyed lookup table.
    array-demo.sh
    #!/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.

  2. Check the script syntax.
    $ bash -n array-demo.sh

    No output means Bash did not find a parse error.

  3. Run the script and inspect the array output.
    $ 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
  4. Use quoted [@] expansion when passing array elements to commands.
    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.

  5. Quote the target when removing a specific array element.
    unset 'files[1]'

    Quoting prevents pathname expansion from treating brackets as a shell pattern before unset receives the array subscript.

  6. Count elements with ${#array[@]} when later script logic depends on the current array size.
    printf "file count: %s\n" "${#files[@]}"