6 thoughts on “Writing Robust Shell Scripts Article

  1. Another technique I use to handle whitespace on shell scripts is to put each value on a line and then use read inside while loops:

    echo “$LINES” | while read value; do
      echo “The value is ‘$value'”;
    done

    Depending on what you want to do it is quite efective, but keep in mind that this usage seems to create a subshell for the while and the variables used inside the while are not available outside it.

  2. David weinehall
    on said:

    if [ “$filename” == “foo” ];

    contains 2 bugs (1 if you use set -u);
    if $filename is unset, this will fail,
    and == is a bashism, use = instead, like this:

    if [ x”$filename” = x”foo” ];

    function foo { for i in “$@”; do echo $i; done }

    should preferably be written

    foo() { for i in “$@”; do echo $i; done }

    instead, since function is also a bashism.

  3. madduck
    on said:

    If writing bash shellscripts, I suggest using [[ and ]] instead of [ ].

    Then,

      if [[ $a = $b ]]; …; fi

    won’t produce an error if a/b are empty or contain whitespace.

  4. Only problem is that [[ isn’t posix:

    mimsy david% dash
    $ if [[ “a” = “b” ]]; then echo “true”; fi
    dash: [[: not found
    $ if [ “a” = “b” ]; then echo “true”; fi

Leave a Reply

Your email address will not be published. Required fields are marked *


Time limit is exhausted. Please reload CAPTCHA.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>