Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: why not promote the plague ? (brace|rc|alternative|modern) syntax



Just to be perfectly clear, let me lay out all the options for compound commands. Please correct me if I've gotten any of it wrong.

First, we have the standard syntax that works in any POSIX shell:

    for var in val1 val2 val3; do command1; command2; done
    while command1; command2; do command3; command4; done
    until command1; command2; do command3; command4; done
    if command1; command2; then command3; command4; else command5; command6; fi

The C-style for loop is not part of POSIX, but is common to bash, ksh, and zsh:

    for (( init; condition; increment )); do command1; command2; done

The repeat loop is purely a Zsh innovation not present in the other shells:

    repeat $times; do command1; command2; done

All of the above have an alternative syntax in Zsh that works irrespective of the SHORT_LOOPS option, where you put the condition (if any) in parentheses and the body in curly braces:

    for var (val1 val2 val3) { command1; command2; }
    while (command1; command2) { command3; command4; }
    until (command1; command2) { command3; command4; }
    if (command1; command2) { command3; command4; } else { command5; command6; }
    for (( init; condition; increment )) { command1; command2; }
    repeat $times { command1; command2; }

NOTE: If the conditional command for while/until/if is a single ((...)) or [[...]] test, you don't need the extra parentheses around it.

Finally, we have the Zsh "short" syntax, which works only with setopt SHORT_LOOPS, and only if the body is a single command:

    for var (val1 val2 val3) command1; 
    while (command1; command2) command3
    until (command1; command2) command3
    if (command1; command2) command3;
    for (( init; condition; increment )) command1;

NOTE: again, the parentheses can be omitted around a single ((...)) or [[...]] test. Also, as far as I know, there's no way to attach an else to an if when using the short syntax. 

On Sat, Dec 14, 2024 at 2:29 AM Marc Chantreux <mc@xxxxxxxxxx> wrote:
On Fri, Dec 13, 2024 at 07:07:17PM -0500, Lawrence Velázquez wrote:
> Mikael's point was to distinguish between the alternative forms
> and the SHORT_LOOPS forms.  None of your examples works without
> SHORT_LOOPS

thanks for noticing. which leads me to open zshmisc(1) and read
read "ALTERNATE FORMS FOR COMPLEX COMMANDS". TIL that my coding
style is actually a mix of the alternative form and SHORT_LOOPS
and the difference is subtile:

        « The  short  versions  below only work if sublist is of the form `{
        list }' or if the SHORT_LOOPS option is set »

regards
--
Marc Chantreux



--
Mark J. Reed <markjreed@xxxxxxxxx>


Messages sorted by: Reverse Date, Date, Thread, Author