Previous Section  < Day Day Up >  Next Section

15.2. Style Issues

Although it is not required, style can make all the difference in how quickly you find bugs in your program. Here are some simple guidelines:

  • Put comments in your program so that you and others know what you are trying to do. A cute little trick today may be an time-consuming enigma tomorrow.

  • Define variables with meaningful names and put them at the top of the program to help detect spelling errors and null values. Names like foo1, foo2, and foo3 really don't say much. Check that you are not using reserved words and pay attention to case sensitivity.

  • Whenever you use a conditional or looping command, indent the statement block that follows, at least one tab stop. If conditions or loops are nested, indent further. Align ending keywords with conditional and looping commands such as if and endif, if and fi, while, done, and so on. (See "Missing Keywords" on page 976 and "Indentation" on page 976.)

  • Use the echo command in areas where you keep getting a syntax error, or turn on the echoing and verbose switches to trace your program's execution. (See "Tracing with Shell Options and the set Command" on page 1009.)

  • Logic errors can be a source for hidden glitches in your program, even if the program runs without error. Know your operators. They vary from shell to shell and are often a cause for a logic error.

  • Make your program robust—check for all possibilities of human error, such as bad input, insufficient arguments, nonexistent files, and the like. (See "Logic Errors and Robustness" on page 1001.)

  • Keep things short and simple when testing. For example, if you are using a function, test the syntax, and then try it with a small script to see if you are getting what you want.

  • Know your operating system commands. Because most statements consist of UNIX/Linux commands, go to the command line and try the command before using it in a script if you are not sure about how it behaves. Do you understand its exit code, how variables are being interpreted, how to use quotes properly, how to redirect output and errors?

  • Last, if you are a system administrator, test your script carefully before taking it to the system level. An unexpected error could bring a whole system to its knees.

The following guidelines will help you with all of these issues and give you a list of the most common syntax errors for each shell, what caused it, and how to fix it.

    Previous Section  < Day Day Up >  Next Section