Scripting From the Command Line

One of the techniques I use to be effective at Unix systems administration is scripting from the command line. If you understand Bourne shell’s for-loops and while statements, it is just one small step from only using them inside scripts to using them on the command line as part of an ad hoc mini-script. It makes sense, does it not? We use shells for both scripting and command line interaction all the time, and if you do both a lot you should notice that they use the same syntax.

Note that I use the Z Shell (zsh), which is a Bourne compatible shell. These examples should also work in the Bourne shell (sh), the Kornshell (ksh), and the Bourne Again shell (bash). They will not work in the C Shell (csh) or the Tenex C Shell (tcsh). Those shells use a different syntax to accomplish the same thing.

If you want to run a program on one remote computer, you can with ssh like so:

workstation% ssh server-01 /usr/local/bin/locate ruby

Now you want to run the same thing on ten hosts (or twenty-five, or perhaps hundreds). You could start by listing them all in a for-loop (note that the ellipses below are not literal—substitute those with the actual system names):

workstation% for M in server-01 server-02 ... server-10; do
workstation for% ssh $M /usr/local/bin/locate ruby
workstation for% done

And there you go, and all done from the command line! You can build things up even higher. Now let us say you put your hosts into a file called HOSTLIST:

workstation% for M in `cat HOSTLIST`; do
workstation for% ssh $M /usr/local/bin/locate ruby
workstation for% done

You can add more logic in the middle of your loop. This mini-script generates a list of systems that do not have their Ruby installed at a particular location:

workstation% for M in `cat HOSTLIST`; do
workstation for% LOCATION=`ssh $M /usr/local/bin/locate ruby`
workstation for% if [ $LOCATION != /usr/local/bin/ruby ]; then
workstation for if% echo "$M: Ruby at non-standard location: $LOCATION"
workstation for if% fi
workstation for% done

Somewhere along the line here you might decide to move this script into a file of its own, but that is up to you to decide. Whether or not I do so depends on how likely it is that I will use the ad hoc script again and how long it is. In the example above, how often do you need to check that a particular program is at a particular path? For me it is not very often, so I end up doing it with this kind of mini-script. Perhaps you are always checking paths as part of regular audits, though, and thus would move the script to its own file to make it available for repeated use. You will figure out the right thing to do in your environment. 😉

  • You can skip to the end and leave a comments. Trackback is currently closed.
  • Trackback URI: http://cosine.org/2007/09/05/scripting-command-line/trackback/
  • Comments RSS 2.0

Leave a Reply

You must be logged in to post a comment.