Rob*_*ark 23 bash zsh while-loop expansion
如何修改以下代码,以便在zsh中运行时,它会一次扩展$things并遍历它们?
things="one two"
for one_thing in $things; do
echo $one_thing
done
Run Code Online (Sandbox Code Playgroud)
我希望输出为:
one
two
Run Code Online (Sandbox Code Playgroud)
但如上所述,它输出:
one two
Run Code Online (Sandbox Code Playgroud)
(我正在寻找在bash中运行上述代码时获得的行为)
dev*_*ull 43
为了查看与Bourne shell兼容的行为,您需要设置选项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
Run Code Online (Sandbox Code Playgroud)
会产生:
one
two
Run Code Online (Sandbox Code Playgroud)
但是,建议使用数组来生成分词,例如,
things=(one two)
for one_thing in $things; do
echo $one_thing
done
Run Code Online (Sandbox Code Playgroud)
您可能还想参考:
3.1:为什么$ var其中var ="foo bar"不符合我的预期?
另一种方式,也可以在 Bourne shell(sh、bash、zsh 等)之间移植:
things="one two"
for one_thing in $(echo $things); do
echo $one_thing
done
Run Code Online (Sandbox Code Playgroud)
或者,如果您不需要$things定义为变量:
for one_thing in one two; do
echo $one_thing
done
Run Code Online (Sandbox Code Playgroud)
Usingfor x in y z将指示 shell 循环遍历单词列表,y, z。
第一个示例使用命令替换将字符串"one two"转换为单词列表one two(无引号)。
第二个例子是同样的事情,没有echo.
这是一个不起作用的示例,以更好地理解它:
for one_thing in "one two"; do
echo $one_thing
done
Run Code Online (Sandbox Code Playgroud)
注意引号。这将简单地打印
one two
Run Code Online (Sandbox Code Playgroud)
因为引号意味着列表只有一个项目,one two.
您可以使用z变量扩展标志对变量进行分词
things="one two"
for one_thing in ${(z)things}; do
echo $one_thing
done
Run Code Online (Sandbox Code Playgroud)
man zshexpn在"参数扩展标志"下,阅读有关此变量标志和其他变量标志的更多信息.