I have been using this command successfully, which changes a variable in a config file then executes a Python script within a loop:

for((i=114;i<=255;i+=1)); do echo $i > numbers.txt;python DoMyScript.py; done

As each DoMyScript.py itself takes about 30 seconds to run before terminating, I'd like to relegate them to the background while the next one can be spawned.

I have tried what I am familiar with, by adding in an ampersand as below:

for((i=114;i<=255;i+=1)); do echo $i > numbers.txt;python DoMyScript.py &; done

However, this results in the below error:

-bash: syntax error near unexpected token `;'


Drop the ; after &. This is a syntactic requirement

for((i=114;i<=255;i+=1)); do echo $i > numbers.txt;python DoMyScript.py & done
  • 1
    Damn it, 43 seconds too slow :) – Martin von Wittich Sep 20 '13 at 19:35
  • 2
    @MartinvonWittich, a +1 to your answer by way of commiseration ;-) – iruvar Sep 20 '13 at 19:36
  • 4
    While that answers the question, it's probably not what the OP wants as by the time all the python instances have started and initialises they'll all see a numbers.txt containing 255. – Stéphane Chazelas Sep 20 '13 at 19:36
  • 1
    Agreed with @StephaneChazelas, but am not sure what we can really do about it with the information given in the question. A proper solution to that probably needs more context. – a CVn Sep 20 '13 at 19:37
  • 3
    Here's the bash manual reference: gnu.org/software/bash/manual/bashref.html#Lists – glenn jackman Sep 20 '13 at 23:38

Given Stephane's comment on 1_CR's answer, you probably want:

for i in {114..255}; do { echo $i > numbers.txt && python DoMyScript.py; } & done
  • Thanks Glenn. I tried a few variations of your code which I like due to the increased readability, but perhaps due to the extra sleep I needed, it was not working out for me. It would also repeat the last number in the for range... Here's what I am happy with at the moment: for((i=1;i<100;i+=1)); do echo $i > numbers.txt;sleep 3; python DoMyScript.py & done The main question point of getting the process to execute in the background is solved. – ljs.dev Sep 21 '13 at 1:21
  • *of course, I had <= in the original question, so the range you supplied was totally suitable based on the info I supplied. Again, thanks for the different approach – ljs.dev Sep 21 '13 at 1:26

Lose the ;:

for((i=114;i<=255;i+=1)); do echo $i > numbers.txt;python DoMyScript.py & done

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.