help-bash
[Top][All Lists]
Advanced

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

Re: declare -f changes 'elif' to 'else if'


From: Dennis Williamson
Subject: Re: declare -f changes 'elif' to 'else if'
Date: Mon, 21 Feb 2022 11:13:24 -0600

On Mon, Feb 21, 2022 at 10:19 AM Chet Ramey <chet.ramey@case.edu> wrote:

> On 2/21/22 9:27 AM, sukolyn via wrote:
> > hi,
> >
> > here's the picture :
> >
> > $ myFunc() { if test foo; then : ; elif test bar; then : ; else : ; fi;}
> >
> > $ declare -f myFunc
> >
> > myFunc ()
> > {
> >      if test foo; then
> >          :;
> >      else
> >          if test bar; then
> >              :;
> >          else
> >              :;
> >          fi;
> >      fi
> > }
> >
> > `else' should be subordonate(?) to main `if' (i.e. `foo' command), not
> to
> > inner if (`bar' command)
>
> What does this mean? `elif' is just syntactic sugar for `else if'; they are
> equivalent internally. There's no reason to have a special parse tree
> representation for `elif', so when the internal parse tree gets converted
> back to an external form, you get `else if'.
>
> --
> ``The lyf so short, the craft so long to lerne.'' - Chaucer
>                  ``Ars longa, vita brevis'' - Hippocrates
> Chet Ramey, UTech, CWRU    chet@case.edu    http://tiswww.cwru.edu/~chet/
>
>
I think the confusion comes from the indentation, which is not significant
in Bash (or most languages). If there are additional alternatives, Bash
will continue indentation of output of declare -f

myFunc ()
{
     if test foo; then
         :;
     else
         if test bar; then
             :;
         else
             if test baz; then
                 :;
             else
                 :;
             fi;
         fi;
     fi
}

This is functionally equivalent to:

myFunc ()
{
     if test foo; then
         :;
     elif test bar; then
         :;
     elif test baz; then
         :;
     else
         :;
     fi
}

which may be what the OP expected to see (or even with substitution of else
if, but then a bunch of fi that each separate if requires looks confusing
without the extra indentation).

Don't forget to consider using a case statement when it's appropriate.

-- 
Visit serverfault.com to get your system administration questions answered.


reply via email to

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