I'm writing a bash script to execute a python program with different values of parameters 'H' and 'K'. What I would like to happen is that only one instance of 'program.py' runs at a time and subsequent jobs are not started until the previous one finishes.
Here's what I tried -
#!/bin/bash
H="1 10 100"
K="0.01 0.1"
for H_val in ${H}
do
for K_val in ${K}
do
{ nohup python program.py $H_val $K_val; } &
done
done
However, this just loops over all the parameter values without waiting for any one job to finish. Conversely, if I modify the above slightly by taking off the ampersand, I can run each job individually - but not in the background. Any ideas on how to proceed?
Put the
&on the command you want to put in the background. In this context, that might be your whole loop:Notice how the
&was moved to be after thedone-- that way we background the entire loop, not a single command within it, so the backgrounded process -- running that loop -- invokes only one copy of the Python interpreter at a time.The redirections (
</dev/null,>myprogram.log, and2>&1) are equivalent to how nohup would redirect stdout and stderr tonohup.outif they weren't already going to a file (or other non-TTY destination) to ensure that they aren't attached to a TTY; adjust the namemyprogram.logto your preference.