2

How can I tell when a given process exits? Like when it's done running and stuff.

For instance:

# Command 1
wget http://releases.ubuntu.com/14.04/ubuntu-14.04-desktop-amd64.iso

# Command 2
echo "I'm a command"

How would I schedule to have Command 2 run when Command 1 exits?

Hamed Kamrava
  • 6,678
  • 12
  • 35
  • 47
  • by `end` do you mean when the process _exits_? If so, you can use something like `while ! (pgrep -f 'wget.*ubuntu-14\.04-desktop' &> /dev/null); do echo 'waiting for program to exit'; done; echo 'program exited. :)'` – Alexej Magura Apr 21 '14 at 06:21
  • @AlexejMagura `end = terminated` – Hamed Kamrava Apr 21 '14 at 06:23
  • 1
    Got'cha. A more correct term would be either `exits` or `terminates`, as in `when a program exits`. `End`, while not _incorrect_, is an unusual way to describe program termination. – Alexej Magura Apr 21 '14 at 06:24
  • `echo $?` if the value of this command is 0 then your command is successfull runned.If it returns any other number, then it's not successfully executed. – Avinash Raj Apr 21 '14 at 06:26
  • 9
    If you want your 'scheduled' command to _only_ run when `wget` is successful, do something like this: `wget && CMD`. If you only want `CMD` to get run when `wget` _fails_: `wget || CMD`. And if you don't care whether `wget` fails or not: `wget ; CMD` – Alexej Magura Apr 21 '14 at 06:29
  • 5
    And if you know the process ID (pid), you can schedule a command in any shell with `wait (pid); CMD`. – Danatela Apr 21 '14 at 06:37
  • Why do people answer questions in comments instead of writing answers? – 200_success Apr 21 '14 at 10:21

1 Answers1

3

There are several things that you could do here. The most basic thing that you can do on the command line is simply to join the commands Eg (using sleep instead of wget):

sleep 10; echo "Next command"

To do this in the background of the shell and make it possible to enter other commands while the process is running:

{ sleep 10; echo "Next command"; } &

To execute a command once any process that you know the PID of has finished:

wait $pid; echo "Next command"

And to background this:

{ wait $pid; echo "Next command"; } &
Graeme
  • 33,607
  • 8
  • 85
  • 110