Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good equivalent to Perl lists in bash?

Tags:

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 image 517
convex hull Avatar asked Sep 17 '08 00:09

convex hull


2 Answers

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 image 194
Charles Duffy Avatar answered Oct 27 '22 00:10

Charles Duffy


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.

like image 41
emk Avatar answered Oct 27 '22 00:10

emk