Running a sequence of commands one after another

I have a situation where I run two commands (they go into background (nohup)), come back after 2 hours, and if both have completed, run two more commands (again nohup), again come back after 2 hours and run two more commands and so on..

I was wondering if it was possible for me to queue these up, so that after the first two finish, the next two start automatically, so that I don't need to keep checking every 2 hours?

All those are independent programs; they are simulations that are memory and CPU hungry, so I don't want more than two of them running simultaneously at any time.

I run them using a syntax similar to:

nohup mySimulator inputs1.txt
nohup mySimulator inputs2.txt
nohup mySimulator inputs3.txt [after the first two have completed, that is..]

Solution 1:

write a shell script like this:

nohup mySimulator inputs1.txt
nohup mySimulator inputs2.txt
while (ps -A | grep -v grep | grep mySimulator > /dev/null); do sleep 1; done
nohup mySimulator inputs3.txt

Then run it from the shell

It fires up two simulators, then waits until there is no mySimulator on the process list and then continues.

(This was run on a Mac, so depending on your operating system it may need a little tweaking ... ps -A is supposed to print a list of all running processes)

Solution 2:

use the wait command, but don't use nohup.

command1 &
command2 &
wait        # this waits for command1 and command2
command3 &
command4 &

from man bash:

wait [n ...] Wait for each specified process and return its termination status. Each n may be a process ID or a job specification; if a job spec is given, all processes in that job's pipeline are waited for. If n is not given, all currently active child processes are waited for, and the return status is zero. If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last process or job waited for.