Understanding Zsh Arrays
Zsh treats arrays as first-class citizens, allowing you to store multiple values in a single variable. Unlike Bash, which uses indexed arrays with specific syntax, Zsh supports both indexed and associative arrays natively. Indexed arrays are zero-based by default, meaning the first element is at index 0. You can define an array by listing elements separated by spaces within parentheses.
fruits=(apple banana cherry)
echo $fruits[1] # Outputs: apple
echo $fruits[2] # Outputs: banana
When iterating over these arrays, it is crucial to understand how word splitting and globbing interact with your data. By default, Zsh does not split words on spaces unless explicitly told to do so via the Noglob option or by quoting variables. This behavior makes array handling more predictable than in other shells, but it requires careful attention to quoting practices.
Iterating Over Arrays
The most common way to iterate through an array in Zsh is using the for loop. This construct allows you to process each element individually without worrying about index management. The syntax is straightforward and mirrors standard programming loops found in many languages.
for fruit in "${fruits[@]}"; do
echo "Processing $fruit"
done
Note the use of double quotes around "${fruits[@]}". This ensures that each element is treated as a separate item, even if it contains spaces. Without the quotes, Zsh would perform word splitting on each element, potentially breaking items with internal spaces into multiple iterations. For associative arrays, you can iterate over keys or values using similar syntax.
Handling Spaced String Pairs
Often, you need to process strings that contain key-value pairs separated by spaces. Zsh offers robust parameter expansion features to handle this efficiently. You can split a string into an array based on whitespace using the -s flag in parameter expansion or by assigning directly to an array variable.
pair="key value"
read -r key val <<< "$pair"
echo "Key: $key, Value: $val"
This approach avoids the complexity of manual parsing and leverages Zsh's built-in read command. The -r flag prevents backslash interpretation, ensuring that special characters in your data remain intact. This method is particularly useful when processing configuration files or user inputs where structured data is presented as simple text lines.
Avoiding Subshell Scope Issues
A common mistake in shell scripting involves modifying variables inside a pipe or subshell. When you use a pipe, such as cat file | while read line; do ... done, the while loop runs in a subshell. Any changes made to variables within that loop are lost once the loop finishes because the subshell has its own isolated environment.
# Broken: Variables modified here are lost
cat file.txt | while IFS= read -r line; do
count=$((count + 1))
done
echo $count # Will likely be empty or zero
To fix this, use process substitution or redirection instead of piping. Process substitution allows the loop to run in the current shell context, preserving variable changes. Alternatively, you can redirect input directly to the loop using <.
# Correct: Variables persist after the loop
while IFS= read -r line; do
count=$((count + 1))
done < file.txt
echo $count # Correctly outputs the total count
This pattern is essential for any script that needs to accumulate state, such as counting lines, building lists, or tracking errors. Always prefer redirection over piping when side effects are required.
Troubleshooting Common Errors
If you encounter unexpected behavior during iteration, check your quoting and globbing settings. Unquoted variables may trigger filename expansion, leading to errors if no matching files exist. Use the NOMATCH option to control this behavior, or ensure all variable expansions are quoted.
Another frequent issue arises from mixing indexed and associative arrays. Ensure you are using the correct syntax for accessing elements. Indexed arrays use square brackets with numeric indices, while associative arrays use string keys. Confusing these can lead to silent failures or incorrect data retrieval.
For more advanced completion and coloring tips, see Zsh: Partial Colouring Completion with Preserved unmatched parts of LS_COLORS. Additionally, understanding how shell source files are loaded can help diagnose initialization issues that affect array definitions, as detailed in Understanding the Order of Shell Source Files.
Frequently Asked Questions
How do I remove duplicates from a Zsh array?
Zsh does not have a built-in function to remove duplicates directly from an array. However, you can convert the array to a unique set by using parameter expansion with the u flag, such as ${(u)array}. This returns a new array containing only unique elements, preserving the original order of first occurrence.
Can I iterate over associative arrays in Zsh?
Yes, you can iterate over associative arrays using the for loop. You can loop over keys with for key in ${(k)assoc_array} or over values with for value in ${(v)assoc_array}. This allows flexible access to key-value pairs without needing to know the specific keys beforehand.
Why does my variable change disappear after a pipe?
Pipes create subshells in Zsh, meaning commands on the right side of the pipe run in a separate process. Variables modified in that subshell do not affect the parent shell. Use process substitution ((...)) or input redirection (<) to keep the loop in the current shell context.
How do I handle spaces in array elements safely?
Always quote your array expansions using double quotes, such as "${array[@]}". This prevents word splitting and ensures that each element, including those with spaces, is treated as a single unit during iteration or function calls.
What is the difference between $array and ${array[@]}
$array expands to the first element of the array (index 0). In contrast, ${array[@]} expands to all elements of the array, preserving them as separate words. Use ${array[@]} when you need to process every item in the array.