ZSH 迭代包含空格的字符串数组

Ben*_*son 5 zsh array string

我正在尝试编写一个 ZSH 脚本,它将迭代一系列包含空格的字符串。

首先,我将set -A数组:

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

从这里开始,我将尝试使用基本循环对其进行迭代for,确保将数组用引号括起来以处理空格:

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

但是,这会引发以下错误:

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

我已经玩了一段时间,甚至尝试将分隔符设置为“\n”,因为我认为问题是数组使用空格作为分隔符,但甚至这样做:

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

其次是:

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

产生相同的 ZSH 错误。

Mar*_*ert 2

与 无关$IFS。您只是语法错误。

这是您通常迭代数组的方式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
%
Run Code Online (Sandbox Code Playgroud)

或者,如果您实际上需要迭代数组索引,那么您可以这样做:

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

或者像这样:

% for i in {1..$#arr[@]} do; print -- $arr[i]; done
Run Code Online (Sandbox Code Playgroud)

当然,如果您只想将数组的元素打印为垂直列表,那么您根本不需要使用循环:

% print -l -- "$arr[@]"
this is
a test
of the
emergency broadcast system
%
Run Code Online (Sandbox Code Playgroud)