for-loopcommand-linezshparse-error

'For' loop on command line in Z shell ('zsh'): "parse error near `done'"


Why am I getting this error? It seems like good syntax to me.

for f in todo/family/* ; echo "$f" ; done

Output:

zsh: parse error near `done'

This is on the regular command line - not in a file.


Solution

  • Missing do in my command.

    As per CharlesDuffy's comment, this is clearly a typo/missing syntax related problem.

    What I wrote:  for f in todo/family/* ; echo "$f" ; done
    #                                      ^ missing do
    
    Bash expected: for f in todo/family/* ; do echo "$f" ; done
    

    Clearly this error/typo is visible using ShellCheck (another great resource).


    How to check Bash-related syntax errors:

    1. Go to ShellCheck and paste this in:

    #!/bin/sh
    
    for f in todo/family/* ; echo "$f" ; done
    

    You will see the error clearly:

    $ shellcheck myscript
    
    Line 3:
    for f in todo/family/* ; echo "$f" ; done
    ^-- SC1073: Couldn't parse this for loop. Fix to allow more checks.
                             ^-- SC1058: Expected 'do'.
                             ^-- SC1072: Expected 'do'. Fix any mentioned problems and try again.
    

    Add do with a space, just before echo and everything checks out:

    #!/bin/sh
    
    for f in todo/family/* ; do echo "$f" ; done
    

    into ShellCheck - you can see there is no error. Remove the do and you will see what my problem was.

    2. Optionally, you could install the shellcheck command