2
Sep

Using Arrays and For Loops

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

Unix~ ls -lh dir1/file1.php
-rw-r--r-- 1 user group 2.7K May  4 16:47 dir1/file1.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:

for file in ${files[@]}; do ls -lh $file; done

The output from the above command is:

Unix~ for file in ${files[@]}; do ls -lh $file; done
-rw-r--r-- 1 user group 2.7K May  4 16:47 dir1/file1.php
-rw-rw-r-- 1 user group 2.8K Aug 25 15:23 dir2/file2.php
-rw-r--r-- 1 user group 2.4K Mar  7 19:57 dir1/subdir/file3.php

APPENDIX: Working with spaces in array items

If you have spaces within your array items, be sure to surround them with quotes like such:

test=( one "two 2" "three 3 tree" )

On top of that, you’ll need to surround ${test[@]} in quotes like such:

for i in "${test[@]}"; do echo $i; done

Here’s what you’ll get:

Unix~ for i in "${test[@]}"; do echo "==> $i"; done
==> one
==> two 2
==> three 3 tree

If you don’t use quotes, you’ll get this instead (BAD!):

for i in ${test[@]}; do echo "==> $i"; done
==> one
==> two
==> 2
==> three
==> 3
==> tree

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 0 Comment So Far

Share your thoughts, leave a comment!