Loop background job

Bash

Bash Problem Overview


I try to run a background job in a for loop in bash:

for i in $(seq 3); do echo $i ; sleep 2 & ; done

I get error:

bash: syntax error near unexpected token `;'

In zsh the command line works.

Bash Solutions


Solution 1 - Bash

Remove the ; after sleep

for i in $(seq 3); do echo $i ; sleep 2 & done

BTW, such loops are better written on separate lines with proper indentation (if you are writing this in a shell script file).

for i in $(seq 3)
do
   echo $i
   sleep 2 &
done

Solution 2 - Bash

You can put the background command in ( )

for i in $(seq 3); do echo $i ; (sleep 2 &) ; done

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbouguiView Question on Stackoverflow
Solution 1 - BashgammayView Answer on Stackoverflow
Solution 2 - BashsogartView Answer on Stackoverflow