Best Practices for Scripting

To make your script code easy to move from one machine to another and easy to leverage for reuse in future scripts, I recommend that you follow these scripting best practices. These principles are universal and apply not only to shell scripting but also to any script languages that you aspire to learn in the future.

Tip 1—Set your variables at the top of the script
Try to put any environment variables that you want to set near the top of your scripts where you and others can easily find them. For example, you'll notice that in ToolsMenu.bat, I've put the %UtilLocation% variable at the beginning of the script with notes about what it accomplishes. I also set the location of the Microsoft Windows 2000 Server Resource Kit and third-party utilities at the beginning of ToolsMenu.bat, where they're easy to find.

Tip 2—Don't hard-code paths in your scripts
In ToolsMenu.bat, you'll see that the %UtilLocation% variable appears in 12 places. If I had hard-coded a server location instead of using a variable, future changes would have been more difficult to make. Should the source location for my utilities ever change or should I ever need to deply ToolsMenu.bat in another part of the enterprise, the %UtilLocation% variable lets me avoid searching for and replacing each server path.

Tip 3—Modularize and leverage your code
To make your code easier to read, troubleshoot, and modify, break it into small sections. Breaking up the code also helps you leverage the time you spend writing code by making it easier to reuse in future scripts. Use comments liberally to make each module's function clear.

In the ToolsMenu.bat script, I use Echo statements in the modules to do double duty. In addition to giving the user information at runtime, the statements take the place of comments in the script.

Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.