help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] bash lazy evaluation with -a


From: Bob Proulx
Subject: Re: [Help-bash] bash lazy evaluation with -a
Date: Tue, 24 Jun 2014 12:41:46 -0600
User-agent: Mutt/1.5.23 (2014-03-12)

Ken Goldman wrote:
> (checking before I report a bug)

Thanks!  This is the right place for bash help.

> I inherited some code that looks like this:
> 
>       if [ $# -gt 3 -a $3 = "-ks" ];then
>               EC_SIGNING_KEY_SIZE=$4
>       fi

Gack!  :-)  A classic problem of insufficient quoting.

> When I run with 2 arguments, I get:
> 
>       rpm.sh: line 514: [: too many arguments

Yes.  The code insufficiently quotes arguments.

> I think the coder expected the left side of the -a to be false, and thus the
> right side would not be evaluated.  Certainly C code does that.  I suspect
> that my invocation with $3 empty causes the error.

You are mostly correct.  The $3 disappears when there are only two
arguments.  Think about that case and you will see that with the above
the [ command will see:

  [ $# -gt 3 -a = "-ks" ]

If you think about this input it is easy to see that something is
wrong with it.  The problem is that the syntax can't be parsed
correctly.  It doesn't get to the runtime short circuit evaluation
part and can't not execute the right side.  It can't even parse it.
If the $3 were quoted "$3" then it would not disappear and would
remain as an "" empty string.

  [ $# -gt 3 -a "" = "-ks" ]

> Is this implementation dependent and thus a bug, or is my analysis wrong?

I don't think we need to analyze why it is wrong on too many levels.
Simply improve it.  Just fixing the quoting should allow it to work.

        if [ $# -gt 3 -a "$3" = "-ks" ];then
                EC_SIGNING_KEY_SIZE=$4
        fi

Also using -a is a bash'ism.  Fine.  We are on the help-bash list
after all.  But I prefer portable shell code.  This is what I would do
with it:

        if [ $# -gt 3 ] && [ "$3" = "-ks" ];then

Well...  Actually I would probably put real argument parsing into it.
But that would be more invasive changes.  The above is enough to get
you going.

Hope that helps!
Bob



reply via email to

[Prev in Thread] Current Thread [Next in Thread]