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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With