Back to Blog

Zsh Shell Tutorial 12: Arrays — Create, Modify & Iterate Collections

Sandy LaneSandy Lane

Video: Zsh Shell Tutorial 12: Arrays — Create, Modify & Iterate Collections by Taught by Celeste AI - AI Coding Coach

Watch full page →

Zsh Shell Tutorial 12: Arrays — Create, Modify & Iterate Collections

Zsh arrays provide a powerful way to store and manipulate collections of data with 1-based indexing, unlike Bash. This tutorial covers how to create arrays, modify them by appending or removing elements, use associative arrays for key-value pairs, and iterate through arrays efficiently with sorting and filtering techniques.

Code

# Basic indexed array creation (1-based indexing)
fruits=(apple banana cherry)

# Access elements (index starts at 1)
echo "First fruit: ${fruits[1]}"   # apple

# Append an element
fruits+=(date)

# Remove the second element (banana)
fruits[2]=()

# Print all elements
echo "Fruits: ${fruits[@]}"

# Slice array (elements 2 to 3)
echo "Slice: ${fruits[@]:2:2}"

# Sort array values
sorted_fruits=(${(o)fruits})
echo "Sorted fruits: ${sorted_fruits[@]}"

# Declare an associative array (key-value pairs)
typeset -A colors
colors=([apple]=red [banana]=yellow [cherry]=darkred)

# Access associative array value
echo "Color of cherry: ${colors[cherry]}"

# Iterate over keys
for key in ${(k)colors}; do
  echo "$key is ${colors[$key]}"
done

# Build an array from command output
files=($(ls *.txt))
echo "Text files: ${files[@]}"

Key Points

  • Zsh arrays use 1-based indexing, so the first element is at index 1, not 0.
  • Use += to append elements and assign empty parentheses () to remove elements.
  • Associative arrays are created with typeset -A and store key-value pairs.
  • Use ${(k)array} to iterate keys and ${(o)array} to get sorted values.
  • Arrays can be dynamically created from command output by capturing it with $().