Friday, December 16, 2005

Grow a Command, Then Execute It

Let's make a copy of all the files under /etc/ that contain references to httpd, the Apache http daemon.

First, a directory to hold the copies:
mkdir /tmp/Apachefiles
Next, we'll construct the commands, on the fly, by growing a pipeline. Follow along with me by executing these in a terminal window. For each step, just recall the previous line and edit it.

find /etc/ # list all the files under /etc.
find /etc/ | xargs grep -l httpd # look for all those files that contain the string httpd
{ find /etc/ | xargs grep -l httpd; } 2>/dev/null # get rid of annoying warnings
# now transform the list into a series of commands
{ find /etc/ | xargs grep -l httpd; } 2>/dev/null |
perl -lane 'print "cp $_ /tmp/Apachefiles/"'
Okay, these look good. (I've left out all the mistakes I made while developing the pipeline, because I know you would never make any. I do, so command history is my friend.)

Now, how about executing it? We could redirect the output into a file, mark the file as executable, and then execute it as a script.

Or we could just add one step to the pipeline, like this:
{ find /etc/ | xargs grep -l httpd; } 2>/dev/null |
perl -lane 'print "cp $_ /tmp/Apachefiles/"' | bash
I frequently grow a set of commands like this, on the fly, then when I have them right, pipe them into a subshell, which will execute them, one by one.

0 Comments:

Post a Comment

<< Home