11.3. Potential Problems

 < Day Day Up > 

Here are some useful things to watch out for when writing shell scripts. Being aware of them will not only save you time in tracking down bugs but will also make your scripts more robust, more readable, and above all, more maintainable.

  • Don't create massive scripts or functions that try to do everything. Split functionality up into smaller units and place them in functions. This not only makes the code easier to read but makes it easier to debug.

  • Always place the shell execution directive (e.g., #!/bin/bash) at the top of your scripts to ensure they will be run by bash.

  • Don't use reserved words for variable names. This can become very confusing:

    let let="echo" let echo="hello" echo "$echo world"

  • Be careful with whitespace. Attempting the following assignment will not give the expected result:

    cat = 5

  • Don't use the same names for variables and functions:

    function letter {      echo $1etter } letter=letter letter letter

    This causes more confusion that it's worth. While this example is contrived, be on your guard for more subtle examples. To guard against this, try and name your functions using verbs, e.g., function print_letter.

  • Be careful when using the test operator [...]. The following two if statements are not the same, although they look very similar:

             if [ "$var" = 42 ]          if [ "$var" -eq 42 ]

    The first is a string comparison, the second an integer comparison. We suggest using ((...)) for arithmetic comparisons in if statements.

     < Day Day Up > 


    Learning the bash Shell
    Learning the bash Shell: Unix Shell Programming (In a Nutshell (OReilly))
    ISBN: 0596009658
    EAN: 2147483647
    Year: 2005
    Pages: 139

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net