什么是与 bash 中的 Perl 列表等效的东西?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/78592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is a good equivalent to Perl lists in bash?
提问by convex hull
In perl one would simply do the following to store and iterate over a list of names
在 perl 中,只需执行以下操作来存储和迭代名称列表
my @fruit = (apple, orange, kiwi);
foreach (@fruit) {
print $_;
}
What would the equivalent be in bash?
bash 中的等价物是什么?
回答by Charles Duffy
bash (unlike POSIX sh) supports arrays:
bash(与 POSIX sh 不同)支持数组:
fruits=(apple orange kiwi "dried mango")
for fruit in "${fruits[@]}"; do
echo "${fruit}"
done
This has the advantage that array elements may contain spaces or other members of $IFS; as long as they were correctly inserted as separate elements, they are read out the same way.
这样做的好处是数组元素可以包含空格或 $IFS 的其他成员;只要它们作为单独的元素被正确插入,它们就会以相同的方式读出。
回答by emk
Like this:
像这样:
FRUITS="apple orange kiwi"
for FRUIT in $FRUITS; do
echo $FRUIT
done
Notice this won't work if there are spaces in the names of your fruits. In that case, see this answerinstead, which is slightly less portable but much more robust.
请注意,如果您的水果名称中有空格,这将不起作用。在这种情况下,请参阅this answer,它的便携性稍差,但更健壮。
回答by Chris Jester-Young
Now that the answer I like has been accepted as the correct answer, I'll now move into another topic: how to use IFS
for personal gain. :-P
既然我喜欢的答案已被接受为正确答案,我现在将进入另一个主题:如何IFS
用于个人利益。:-P
fruits="apple,orange,kiwifruit,dried mango"
(IFS=,
for fruit in $fruits; do
echo "$fruit"
done)
I've put the code in brackets so that the IFS
change is isolated into its own subprocess; thus at the end of the bracketed section, IFS
is reverted back to its old value. :-)
我已将代码放在括号中,以便将IFS
更改隔离到其自己的子进程中;因此,在括号部分的末尾,将IFS
恢复到其旧值。:-)
回答by JBB
for i in apple orange kiwi do echo $i done