What do I mean by scripts that don't actually do anything? I'm suggesting that in some cases it makes sense to write scripts that don't make any changes to the system. Instead, the output of the script is the list of commands that need to be run for the change to be made. After you have reviewed the commands the script generated you can then actually run the commands to make the changes. I picked this technique up from a coworker (Thanks Merrill!)
To actually make the changes on your system you can either copy/paste the command lines the script generated, or if there is a lot of output, you can redirect the output of your script to a file. You can then review the file and if it looks correct run the commands in the file by using a command such as ksh ./outputfile or bash ./outputfile
I like to use this technique for any scripts I am writing that are making intrusive changes on critical systems.
Here are some of the reasons why:
- You can't script common sense. Even the best programmers write code that contains bugs. Often times your script will run in to a corner case that you never considered and the results can be disastrous. If your script simply outputs the commands to be run it allows a person to quickly verify that everything looks correct before the commands are run.
- It allows for quicker development. Since your script doesn't actually change anything on the system you can run it over and over very easily.
- Often times you can run the script without root access. Again, this is because your script isn't actually making changes. This can make developing and running the script even safer.
- It allows you to easily document your changes. If you run the script and redirect the output to a file, you can then review the file, and if it looks correct have the shell run the file. You are left with a file that documents exactly what was done.
The best of both worlds.
It is very easy to take the script and actually have it make the changes on the system without your intervention. Maybe you feel confident in the script after running it many times or perhaps you are on a test/dev system which isn't that important. All you have to do to actually have the script make the changes is pipe its output to the shell interpretor.
./myscript.sh | ksh
./myscript.sh | bash
The script will run and output the commands that need to be run and the shell will read this from the pipeline and actually run the commands.