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

Re: bash vs. python scripts - which one is better?



Manon Metten wrote:
> David Brodbeck wrote:
> > It certainly has its warts.  In particular, Bash's "test" (aka "[")
> > operator has pitfalls.

The test command was originally not a shell built-in.  It was an
external standalong /bin/test command.  For performance reasons it has
been incorporated into the shell but the interface can't change or it
would break compatibility.  That is a core reason why the shell single
bracket test operator has warts and why the new double bracket test
operator was created.

> > Testing for an empty variable, for example,
> > is awkward.  If you do:
> >
> > if [ $foo == "" ]
> >
> > Bash will complain about missing arguments.

Careful!  "==" is valid bash but is not valid POSIX sh.  In Bash the
double equal can be used as a synonym for the single equal but not in
POSIX shell.

> > Instead, you have to do something like this:
> >
> > if [ "x$foo" == "x" ]

But better to use the one = so that it is portable.  I prefer using an
underscore to hide it more but 'X' is the tradition.

  if [ _"$foo" = _"" ]

> > which works, but makes no sense the first time you see it.

Right.  I prefer using the test -n or -z options.  This is effectively
an external command so still needs to be quoted though.  But I find
this much more clear on casual reading.

  if [ -z "$foo" ]

Use double brackets to get the new internal to the shell test not
needing quoting.

  if [[ -z $foo ]]

However this does not actually say if the variable is set but only if
it is zero length.  If it is important if the variable is set but set
to an empty string then things get more obscure.

  if [[ ${foo+set} != set ]]; then echo foo is not set; fi

> Thanks. I copied this to my 'Bash-howto'.

I would hate to see you record this in your howto with "==" without
knowing that "==" is a bash specific feature.  :-)

Bob



Reply to: