Bash arrays store several words under one variable name. Indexes start at zero.

Program

Play the script to watch an array provide one element and a count.

arrays.sh
Replay: real traced execution (multi-file project)
#!/usr/bin/env bash

tasks=("lint" "test" "package")
first="${tasks[0]}"
count="${#tasks[@]}"
echo "$first/$count"
  1. tasks ← [lint, test, package]

    3tasks=("lint" "test" "package")4first="${tasks[0]}"
    values this step[lint, test, package]tasks
  2. first ← lint

    3tasks=("lint" "test" "package")4first="${tasks[0]}"5count="${#tasks[@]}"
    values this steplintfirstlinttasks[0]
  3. count ← 3

    4first="${tasks[0]}"5count="${#tasks[@]}"6echo "$first/$count"
    values this step3count[lint, test, package]tasks
  4. echo "$first/$count"

    5count="${#tasks[@]}"6echo "$first/$count"
    outputlint/3
    values this steplintfirst3count

Read One Element

  1. tasks stores lint, test, and package.
  2. Bash array indexes start at 0.
  3. ${tasks[0]} reads lint.
  4. ${#tasks[@]} counts all three tasks.
  5. The script prints lint/3. | Index | Task | | --- | --- | | 0 | lint | | 1 | test | | 2 | package |
array An array stores multiple values and retrieves each by index.
array length `${#array[@]}` expands to the number of array elements.

Exercise: arrays.sh

Read the first task from an array, count all tasks, and print both values