在 zsh 中循环退出

for cicle exit in zsh

我最近将我的默认 shell 从 bash 更改为 zsh,我在 bashrc 中有一个函数用于定位文件和执行文件。 bash 函数没问题,但是 zsh 我的变量是空的,特别是变量 $only_file:

comp=$(locate -i -b -r "\.appimage$")

only_file=$(for x in $comp; do if [[ -f $x ]]; then echo $x; fi; done)

$only_file 为空。 我尝试了不同的“变体”(单行):

for x in "$comp"; [[ -e $x ]] && echo $x done;

for x in "$comp"; [[ -f $x ]] && echo $x

for x in $comp; do if [[ -f $x ]]; then echo $x; fi; done

都没有打印结果。所以我只尝试了for循环:

for x in "$comp"; echo $x

没关系。我试过了:

[[ -f "/path/to/file" ]] && echo "file" || echo "ERROR"

和回显文件;然后:

[[ -f "/path/to/directory" ]] && echo "file" || echo "ERROR"

并回应错误。所以我认为有什么东西打破了 for 循环,我清理了列表 ($comp) 并只放置文件(对于始终为真的 -f 测试),结果相同(void $only_file);我在里面放了一个 continue if:

for x in $comp; do if [[ -f $x ]]; then echo $x; continue; fi; done

同样的结果。现在我不知道,有人可以解释我做错了什么吗? 谢谢

您是否知道在 zsh 中,您的 for 循环将始终恰好 执行一次?因此,除非 $comp 中存储的字符串恰好是现有文件的名称,否则 only_file 将为空。

在bash中,$comp的内容会进行分词,每个词执行一次循环体

zsh中你可以通过

达到同样的效果
for x in ${(z)comp}