Sunday, November 11, 2007

Editing Startup Scripts on Solaris - Part 3 - The VI Way

As we mentioned earlier, using Sed, Awk or command line Perl to edit your source startup files in /etc/init.d is a perfectly acceptable practice. However, because of Solaris' tendency to use hard links in their "run level" directories, this can cause problems, as using these utilities changes the "inode number" of the source file and separates it from the "run level" script.

The answer is to do the simplest thing. Edit all the source files using an editor, like vi. If you edit them in this way, after your changes have been made and you've saved your edits, the inode number will be the same. The reason this usually isn't considered an option is that, if you have to comment out a large number of scripts, using vi can be very time consuming and can put you in a position to make a single error, or multiple errors, in some of your source scripts, since you'd have to repeat the same editing actions over and over again.

Here's a little piece of script that can make it so you can use vi to comment out your scripts (preserving the inode number) and not have to worry about making a hard-to-find error somewhere along the way. This way, like with Sed, Awk or command line Perl, you'll either do everything right or make the same mistake in all files ;)

This example uses the "here document" (referred to in this blog, in a previous post here) and inserting actual control characters (referred to in a separate earlier post here). For our purposes, since this script doesn't translate well into simple text, we'll use a basic legend:

[ctl-v] will mean hit the "control" and "v" keys at the same time.
[esc] will mean literally hitting the "escape" key.
[cr] will mean literally hitting the "return," or "enter," key.

And here it is - The script takes the arguments of any number of files that you want to totally comment out; placing "#" characters in the first position on every line.

#!/bin/sh

for x in $@
do
/usr/bin/vi $x <<-END
[ctl-v][esc]:g/^/s//#/[ctl-v][cr]][ctl-v][esc]:wq![ctl-v][cr]
END
done


Now you can run "Yourscript filea fileb filen..." and you will actually be doing real editing with vi,completely hands-off :)

P.S. If you don't want to see the vi output, and you're satisfied that the script is working as expected, just change the following line

from: /usr/bin/vi $x <<- END
to: /usr/bin/vi $x <<- END >/dev/null

, Mike