【问题标题】:for cicle exit in zshzsh中的cicle退出
【发布时间】:2020-11-04 17:02:56
【问题描述】:

我最近将我的默认 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);如果:

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

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

【问题讨论】:

    标签: bash for-loop sh zsh


    【解决方案1】:

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

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

    zsh 中,您可以通过执行 a 来达到相同的效果

    for x in ${(z)comp}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 2021-09-27
      • 2020-05-11
      • 1970-01-01
      • 1970-01-01
      • 2020-12-22
      • 2018-01-07
      相关资源
      最近更新 更多