In perl one would simply do the following to store and iterate over a list of names
my @fruit = (apple, orange, kiwi);
foreach (@fruit) {
print $_;
}
What would the equivalent be in bash?
In perl one would simply do the following to store and iterate over a list of names
my @fruit = (apple, orange, kiwi);
foreach (@fruit) {
print $_;
}
What would the equivalent be in bash?
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 answer instead, which is slightly less portable but much more robust.
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
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. :-)
bash (unlike POSIX sh) supports arrays:
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.