如何在zsh中一次遍历一个单词 [英] How to iterate through string one word at a time in zsh

查看:46
本文介绍了如何在zsh中一次遍历一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何修改以下代码,以便在 zsh 中运行时扩展 $things 并一次遍历它们?

How do I modify the following code so that when run in zsh it expands $things and iterates through them one at a time?

things="one two"

for one_thing in $things; do
    echo $one_thing
done

我希望输出是:

one 
two

但是正如上面写的,它输出:

But as written above, it outputs:

one two

(我正在寻找在 bash 中运行上述代码时您得到的行为)

(I'm looking for the behavior that you get when running the above code in bash)

推荐答案

为了查看与 Bourne shell 兼容的行为,您需要设置选项 SH_WORD_SPLIT:

In order to see the behavior compatible with Bourne shell, you'd need to set the option SH_WORD_SPLIT:

setopt shwordsplit      # this can be unset by saying: unsetopt shwordsplit
things="one two"

for one_thing in $things; do
    echo $one_thing
done

会产生:

one
two

但是,建议使用数组进行分词,例如,

However, it's recommended to use an array for producing word splitting, e.g.,

things=(one two)

for one_thing in $things; do
    echo $one_thing
done

<小时>

您可能还想参考:


You may also want to refer to:

3.1:为什么 $var where var="foo bar" 不符合我的预期?

这篇关于如何在zsh中一次遍历一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆