0

I'd like to be able to launch a command now, but have it start only after an older command (which is already running) completes.

For example, say I'm copying a large file over the network, an action that already saturates my network bandwidth. I then want to copy a second large, less important file to the same destination, but in order for the first copy to finish asap I'd like to delay this second copy until after the first finished.

Normally I would do this:

10 minutes ago:
cp large_file_urgent ~/networkmnt/
Present time:
sleep <some_guesstimated_time_for_old_cp_to_finish> && cp large_file_lessimportant ~/networkmnt

Is there a smarter way to do this? Can I somehow tell the second cp to wait until the first cp's PID terminates?

This is on Ubuntu 13.04 (in case that's of any consequence).

1
  • 1
    i think kill -0 is perhaps what you are looking for. just loop it and once the loop exits, your second cp can run
    – driz
    May 15, 2014 at 19:03

3 Answers 3

4

If you know in advance the commands you need to run, you can just do

cp file1 file2; cp file3 file4

If you have already started the first command, and you are in the same shell, you can hit Ctrl+Z, then bg to put the first command in the background, then call wait on the job number or PID to wait until it finishes. For example:

$ sleep 30
^Z
[1]+  Stopped                 sleep 30
$ bg
[1]+ sleep 30 &
$ wait %1; echo "next command"
[1]+  Done                    sleep 30
next command
0
2
cp largefile1 somedestination

...time...passes...

wait $(pidof cp)
cp largefile2 someplace

The bash builtin wait, will pause until the job/process specified (or all jobs if unspecified) has completed before continuing.

1
  • There is also a wait command that does the same thing (excluding shell jobs, of course). May 15, 2014 at 22:40
1

You can check that the process is still running using the /proc filesystem:

while test -d /proc/$cp_pid; do
  sleep 10
done 
cp next_big_file network
1
  • It fails if the PID gets reused in the pause between checks. May 15, 2014 at 22:43

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.