循环后台作业

我尝试在 bash 的 for 循环中运行一个后台作业:

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

我得到了一个错误:

bash: syntax error near unexpected token `;'

在 zsh 中,命令行可以工作。

70661 次浏览

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

You can put the background command in ( )

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

If you want to run a block of code in the background, you could do the below. Just put the block of code around the curly braces.

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