Friday, April 4, 2008

The Noobs Guide to Bash-Scripting - Part 3

Welcome back! This is the third in a series of tutorials aimed at teacher beginners how to make their own bash script. The previous tutorials are located here:

In this tutorial, we will cover:
  • "For" loops

The For Loop

We're going to continue the bash script that we had made last tutorial. In our scenario we are a programmer working with a smallish team of like-minded programmers. We are about to group all the code files together in order to be review and compiled. However, we realize that we have forgotten to sign our name on our files! So we have set of to create a small bash script that would "tag" each file with the our user name.

This is what we have made so far:
echo "//Written By $USER" >> $1
There is one outstanding problem with this though, we have to run the command for each of our code files. Depending how many files there are, this could take a while. So what need is to be able to pass all the files we want to tag, in one argument.

Lets say, for the benefit of this exercise, that all our files are in a single directory. What would you usually do in a command line if you want to perform an operation on many files? Use the "*" (asterisks) of course!

We want to be able to run the script like this:
./tag_script example_directory/*
We covered the argument variables last tutorial, but there is another argument variable that I didn't mention; "$@". This variable contains ALL of the arguments that were used, each variable is referred to as an "element". This combination of all the elements in one variable is what allows us to use the FOR loop.

A FOR loop performs the same action on all the elements inside a variable. It's standard form is this:
for FILE in "$@"; do
A quick breakdown:
  • As I explained before, $@ is our variable that contains many elements
  • The code contained inside the FOR loop will be performed for each of the elements within "$@"
  • FILE is a variable. At the beginning of each cycle through the loop, it will equal the next element in "$@"

An Example:

$@ = "file1","file2","file3"

for FILE in "$@"; do
echo $FILE
The result of this script would be:
Notice, the code contained within the FOR loop was performed on each element of $@. Now it's just a simple matter of applying this in our tagging script.
for FILE in "$@"; do
echo "//Made by $USER" >> "$FILE"

Then we just have to call the script with this:
./tag_script target_directory/*

IMPORTANT: The script will not work at all unless you include the "*"

Thanks for reading again, and I hope you learn something from this exercise. If you've got any questions or suggestions, don't hesitate to email me, raynerw[at]optusnet[dot]com[dot]au. Feel free to link to this site, please don't copy any material on here. Don't forget to check back later for the next tutorial: IF statements.

No comments: