[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: For those who care about my petty little habits in shell scripts [was: About backquotes in shell scripts]



In the same vein, I tend to:
  - quote variables whenever they might hold spaces: "$1" instead of $1;

  - use "$@" instead of $* for the same reason: "$@", as weird as it can
    seem when you first look at it, expands to "$1" "$2" "$3" etc.
    (_every_ parameter becomes quoted on its own, hence embedded spaces
    in parameters are preserved)---which is most of the times exactly
    what is needed;

  - always quote variables in tests if you cannot predict for sure that
    they contain no space. For instance, the following line is unsafe:

       if [ $str = foobar ]

    because in case the variable 'str' contains a space, you will get a
    weird error because the '[' command will find too many arguments
    since $str expands to several words.

  - use the -z and -n tests instead of weird constructs such as:

      if [ ! "X$foobar" = "X" ]

    This one is replaced by 'if [ -n "$foobar" ]' and its friend:

      if [ "X$foobar" = "X" ]

    is replaced by 'if [ -z "$foobar" ]'. These are fairly easy to
    remember:

       -z -> 'is Zero'
       -n -> 'is Not null'

-- 
Florent



Reply to: