4

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
%
Marlon Richert
  • 2,029
  • 3
  • 18
  • `identity="iPhone Distribution: Apple Inc."; command=(codesign -fs $identity Payload/xx.app); $(echo $command)`, how can I treat `$identity` as a single string? – DawnSong May 17 '22 at 08:05
  • Solution: embrace with quotes and use `eval` to explain the quotes correctly, i.e, `folder="My Pictures"; command=(ls -l \""$folder"\"); eval "$command[*]"` – DawnSong May 17 '22 at 08:21
  • If you are using `eval` for _anything,_ that’s usually a sign you’re doing it wrong. Just use `"$identity"`, with double quotes. – Marlon Richert May 18 '22 at 13:57