When you find yourself putting in commands over and over, you can use the foreach statement that executes a code block for each data item in an array. An array is a set of elements indexed sequentially that have the same type of data. Most times, each element of an array has a unique identifying index number. Changes made to one element of an array do not affect the other elements. foreach specifies that for each entry in the array of entries, Unix will output the entries to the terminal. Commonly, foreach is used in place of a standard for loop. Unlike this for loop construct, however, a foreach loop usually does not specify the order in which the items are considered.
The point of this is, if you don't want to spend a massive amount of time inputting files into a command to automate them, you can use the foreach command, which takes a list of files, and does something "for each" of them based on what you specify. The commands' use is much easier to demonstrate than to explain. If you have a list of files that you need to do something to, you can follow these steps to use foreach:
This can be seen as
> foreach test (directory1 directory2 directory3) ? tar -cvf $test.tar $test ? end
Your machine responds by running the tar command for each file you gave it to work with. Inside the foreach command loop, note the use of the expression $test. foreach goes through the list of filenames you gave it and puts each one sequentially in the test variable. To use the contents of a variable in the shell, put a $ sign before it. For example, foreach first puts mydirectory1 in the variable test. It then runs the tar command, and the shell expands the test variable to directory1. The tar command that gets executed actually looks like the following: tar -cvf mydirectory.tar mydirectory. The next time through the loop, foreach puts directory2 in the variable test, and the process is repeated.
You can use REs in the shell instead of enumerating the filenames to use the foreach command. If you notice in the previous example, all the directories you want to tar actually have part of their names in common directory. If you wanted to produce the same results without having to enumerate all the directory names to foreach, you might issue the preceding foreach command as follows: foreach test (*directory).
It's easy to see how you can use Unix to control process, and now, you should start to see the granular level of control Unix can give you over what it is you do work on. You can fine-tune, tweak, and customize your system once you know how to master these fundamentals. Now that you are familiar with the foreach command, let's look at conditional statements such as while and if.