Writing Robust Shell Scripts Article

I’ve just finished writing an article on tips for making your shell scripts more robust. Comments welcome.

Filed under computing

Tagged articlebashshell

6 comments

Comments are closed. These are preserved from the original site.

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.

Useful article. Linked from URL given.

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.

The title is "Writing Robust Bash Shell Scripts". I think bashisms are allowed in that context. :)

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.
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