Tutorials, Guides, Tips, and Tricks from Everyday Experiences

Here’s how to setup an array and use it in a for loop. Open up the terminal and let’s get started…

Step 1: Create an array

This is easily done by surround space separated items in parenthesis. For example:

files=( dir1/file1.php dir2/file2.php dir1/subdir/file3.php )

Note: Be aware of any spaces within the array items. If you have this, you’ll need to surround it in quotes. See appendix at the end of this post.

Step 2: Figure out what you want to do to each of the items in the array

The next part is figuring out what you want to do to each of the items in the array. Keep in mind, these items can be variables, filenames, text, numbers, whatever. For example, I want to see how large each of these files are along with other information. For this, I would run ls -lh filename.php

Step 3: Iterate through the list of array items

Finally, let’s perform the action from step 2 on all of the items in our array. For this, the key is to use ${array[@]}, which says run through all (@ll) of the items in the array called “array”. Going along with the contrived, simple example set in the previous steps, the final command is: