Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Let's imagine I have a client and a server on the same machine, and I'd like to script some interaction between them.

I would really like a shell script to -

  1. Start server
  2. Put server in the background
  3. Start client
  4. (wait for client to do whatever it does)
  5. Stop server

I can do most of that already, like this -

./server &

But that leaves server running after the script finishes which, apart from anything else, is very untidy.

What can I do?

share|improve this question
up vote 4 down vote accepted

You can use bash job control:


./server &
kill %1

Be sure to put the #!/bin/bash at the beginning of the script so that bash is used to execute the script (I'm not sure if job control is supported in sh, please correct me if it does).

share|improve this answer
Thanks! That's exactly what I needed. – Jez Jul 15 '11 at 15:57
No problem! Glad to help! – Wuffers Jul 15 '11 at 15:59

You can achieve the same result with standard POSIX sh. In sh, when you spawn a process in the background using '&', the PID of the process is stored in the special variable $!. So:

./server &
kill $!

For more complex situations you might want to save the pid:

./server &
# ... lots of other stuff
kill $serverpid
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .