5

I am trying to write a ZSH script which will iterate through a series of strings that contain spaces.

First, I'll set -A the array:

set -A a "this is" "a test" "of the" "emergency broadcast system"

From here, I'll try to iterate through it using a basic for loop, making sure to wrap the array in quotes to handle the spaces:

for i in "$a"; do echo "${a[$i]}"

However, this throws the following error:

zsh: bad math expression: operator expected at `is a test ...'

I've been playing around with this for a bit, even trying setting the delimiter to "\n" since I think the issue is the array is using spaces as delimiters, but even doing:

a=(IFS=$'\n';"this is" "a test" "of the" "emergency broadcast system")

followed by:

for i in "$a"; do echo "${a[$i]}"; done

yields the same ZSH error.

1 Answers1

2

It has nothing to do with $IFS. You are simply getting the syntax wrong.

This is how you would normally iterate over an array in zsh:

% arr=( 'this is' 'a test' 'of the' 'emergency broadcast system' )
% for str in "$arr[@]"; do print -- $str; done
this is
a test
of the
emergency broadcast system
%

Alternatively, if you actually need to iterate over the array indices, then you could do it like this:

% for (( i = 1; i <= $#arr[@]; i++ )) do; print -- $arr[i]; done

Or like this:

% for i in {1..$#arr[@]} do; print -- $arr[i]; done

Of course, if you just want to print the elements of the array as a vertical list, then you don't need to use a loop at all:

% print -l -- "$arr[@]"
this is
a test
of the
emergency broadcast system
%