Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to background tasks within a bash loop

Given the following bash loop:

for ((x=1; x<=$y; x++)); do echo $x; done
1
2
3
4

How to "background" the individual tasks?

09:25:58/~ $for ((x=1; x<=$y; x++)); do echo $xi &; done
-sh: syntax error near unexpected token `;'

I tried "bash"ing the echo and that did not work either:

09:26:37/~ $for ((x=1; x<=$y; x++)); do bash -c "echo $x" &; done
-sh: syntax error near unexpected token `;'
like image 395
WestCoastProjects Avatar asked Jun 09 '26 12:06

WestCoastProjects


1 Answers

Both & and ; are command terminators in the shell.

You only need to terminate each command once. So don't use both together:

for ((x=1; x<=$y; x++)); do echo $x & done

You would get the same error by using two ;s as well:

$ for ((x=1; x<=$y; x++)); do echo $x ; ; done
-bash: syntax error near unexpected token `;'

Note that trying to use ;; gets a different error because ;; is a special token to the shell (used in case statements):

-bash: syntax error near unexpected token `;;'

Shell grammar:

%start  complete_command
%%
complete_command : list separator
                 | list
                 ;
list             : list separator_op and_or
                 |                   and_or
                 ;
....
separator_op     : '&'
                 | ';'
                 ;
separator        : separator_op linebreak
                 | newline_list
                 ;
like image 75
Etan Reisner Avatar answered Jun 11 '26 23:06

Etan Reisner