Arrays

View saved

Indexed arrays

Bash arrays hold multiple values. Quote "${arr[@]}" when expanding.

files=("a.txt" "b c.txt" "d.txt")
for f in "${files[@]}"; do
  echo "$f"
done

Length and indices

Count elements and access by index.

echo "count=${#files[@]}"
echo "first=${files[0]}"

Appending

Add items as you discover them.

files+=("e.txt")
printf '%s\n' "${files[@]}"

mapfile peek

Read lines into an array with mapfile / readarray.

mapfile -t lines < input.txt
echo "${lines[0]}"

Comments

One comment per signed-in account. Comments are saved with this page’s URL.