Jumping Through Loops
By Noel Davis
A technique that I picked up from a good friend of mine a while back is to type in a loop at the command line to quickly do a repetitive task and save time and effort.
It's a common technique to use a loop in a shell script.
This script reads a list of files stored in InputFile, loops through each line and execute "ls -l" on each cycle.
for i in `cat InputFile`
ls -l $i
The cool thing is you can use the same loop from the command line.
For example a few weeks ago we were having trouble with a resier filesystem that is used for data uploads by our Oracle DBAs. They needed to upload files and I needed to have a bunch of time to do a backup of the filesystem before I did the --rebuild-tree with reiserfsck.
So I did something like this:
# cd work
Basically this makes a listing of all the directories and subdirectories in the /work filesystem, loops though them and recreates the directories, and then sets the owner and the group. Once all the directories are created I moved the /work mount point to /work-bad and made a symbolic link from /work to the directory I created in /i07. I then edited fstab to move the mount point from /work to /work-bad.
# find . -type d >/root/dir-list
# cd /i07
# mkdir work-new
# cd work-new
# for i in `cat /root/dir-list`
# mkdir $i
# chown oracle.dba $i
# cd /
# mv work work-bad
# ln -s /i07/work-new work
# vi /etc/fstab
I used a symbolic link for several reasons. First there is more than one system administer here and I felt that a symbolic link would be more obvious when they came in the next day. Second this was a temporary change that would be moved back once the original work filesystem was repaired. Finally there are other directories and data on the /i07 filesystem and I needed to not break other things fixing /work.
A situation that this approach is not as good for is one were the changes are destructive and the penalty for a typo would be painful. In cases like this I sometimes write a script even if it is easily done from the command line. By doing this I can go back and double check the script for errors before executing the commands.
There are of course many different techniques that can solve the problem given in the example.
If you don't use loops from the command line give it a try. You will find it saving you time and effort on a regular basis on tasks that you only have to do once.