Indexed arrays (bash and zsh)
files=("a.txt" "b.txt" "c.txt")
echo "${files[0]}" # a.txt (bash) or empty (zsh — see below)
echo "${files[@]}" # all elements
echo "${#files[@]}" # count: 3
files+=("d.txt") # append
unset 'files[1]' # remove the b.txt slotbash arrays start at 0, zsh at 1 by default. Add setopt KSH_ARRAYS in zsh to get bash semantics. The difference catches everyone the first time.
Iterating
for f in "${files[@]}"; do
echo "$f"
done
# With index
for i in "${!files[@]}"; do
echo "$i: ${files[i]}"
doneAssociative arrays (bash 4+, zsh)
declare -A user
user[name]="Pippa"
user[age]=24
for k in "${!user[@]}"; do
echo "$k = ${user[$k]}"
donemacOS bash 3.2 doesn't have associative arrays. Either install bash 5 via brew, or use zsh, or fall back to parallel indexed arrays.
Reading a command into an array
readarray -t lines < ~/.zshrc # bash 4+
lines=("${(@f)$(< ~/.zshrc)}") # zsh
files=(*.txt) # globSlicing
echo "${files[@]:1:2}" # 2 elements starting at index 1
echo "${files[@]: -1}" # last element (note the space)