23

I wonder why there is an error using an asynchronous command within a loop?

$ for i in {1..8}; do sleep 100 & ; done
bash: syntax error near unexpected token `;'

If I write it as

$ for i in {1..8}; do 
> sleep 100 & 
> done

this works fine.

How can I write it in one line without error?

38

Drop the ;:

for i in {1..8}; do sleep 100 & done

& separates commands, so the ; is extraneous (and the shell expects something between & and ;).

  • Thanks. "the shell expects something between & and ;", so why isn't an empty command ok between & and ;? – Tim Sep 18 '17 at 13:48
  • 5
    The real no-op command is : – HTNW Sep 18 '17 at 16:20
  • 1
    @StephenKitt, the section you reference also states: "In an interactive session or a script with other commands, extra <newline> or <semicolon> characters...would not qualify as the empty command described here because they would be consumed by other parts of the grammar." Hmmm... – Wildcard Sep 19 '17 at 5:13
  • 1
    @Wildcard that’s interesting, I hadn’t thought through the consequences of that sentence when researching the answer to Tim’s follow-up. Enabling Bash’s POSIX mode doesn’t change its behaviour in this regard. Hmmm indeed... – Stephen Kitt Sep 19 '17 at 5:29
  • 2
    @Wildcard: echo foo ; ; echo bar in bash 4.4 says syntax error near unexpected token `;'. dash gives a similar error. In this case, it is an empty command because no other part of the grammar consumes it. I think they might be talking about redundant ; at the end of a line like sleep 100; (newline). – Peter Cordes Sep 19 '17 at 8:07
22

Group your do actions in curly brackets:

for i in {1..8}; do { sleep 100 & }; done

Easy to understand for you as well as for Bash!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.