I like bash.

It is simple and straight forward. In the words of Master Foo, “Is it he who writes the ten thousand lines, or he who, perceiving the emptiness of the task, gains merit by not coding?”

One of the easiest things to do in a bash script that has more than one function is to add the capability of the script to allow arguments to specify it’s action.

You’ll notice, if you look at an init script (for instance, /etc/init.d/httpd on a Red Hat server), that roughly this same method is used to allow for arguments like “start” and “stop” et al.

I was working on an LFS installation, and scripted a little foo to get the sources and patches without having to manually download each one. Basically, it used this command to parse the pages with the listings of source tarballs or patches, and find the URL:

lynx -source file:///home/chuck/src/lfs-clfs/book/ppc/materials/packages.html | grep -A1 Download: | grep -v Download: | awk -F’”‘ ‘{print $2}’ | grep -v ‘^$

As you can see, I downloaded the book source so that I wouldn’t spam their site (a little Internet courtesy). I was presented with a list of links to source files. Hooray!

I expanded into cross-compiling linux for a PPC laptop I had laying around, and ended up needing to expand my script to be able to tell it which sources and patches to download. After a little research, I came across the “case” control statement. In the case statement, I was able to specify which sources and/or patches I wanted by adding an argument to the script. Here is the case statement:

case $1 in
gens)
ARGS=$GENERAL_SOURCES
;;
genp)
ARGS=$GENERAL_PATCHES
;;
ppcs)
ARGS=$PPC_SOURCES
;;
ppcp)
ARGS=$PPC_PATCHES
;;
all)
ARGS=`echo $GENERAL_SOURCES $GENERAL_PATCHES $PPC_SOURCES $PPC_PATCHES`
;;
*)
ARGS=”"
;;
esac

As an added bonus, you can see that on the last argument (denoted by “*)”), I was able to catch all other arguments besides the ones I specified. If the argument didn’t match what was supposed to be there, it would set the $ARGS variable to NULL, or “”.

With a little “if/else” statement, I then was able to specify that if the $ARGS variable had no value, to echo the usage of the script, or else run the command and download my sources.

Bear in mind, though that the $ARGS variable should be subject to some pretty good input checking before putting a script like this into production, because someone could easily hack it:

$ ARGS=”(rm -rf /)”; ./script.sh

WARNING: do NOT run the above command, as your box will be broke! I will not fix it for you! You’ve been warned!

/cs