0

I'm trying to build a bash script that runs unit tests on a web server.

I wish to run a simple bash script that could be (for example) in a makefile that does the following:

  1. Start a web server
  2. Run the unit tests
  3. Stop the web server

Assuming that the web server is written for NodeJS, here's what it could look like:

npm start &
sleep 5
npm test

The issue with this approach is that the web server will keep on running. How do I stop it after the npm test stage?

goncalotomas
  • 1,000
  • 1
  • 12
  • 29
  • 1
    Have you considered a `killall`? – Jonathan Wheeler Dec 12 '16 at 00:31
  • Not really an option. If I understand correctly, `killall` kills all processed that match a keyword you specify. If that's correct, trying to kill my background process would possibly kill others that I wish to leave untouched. Please correct me if that's not what `killall` does :) – goncalotomas Dec 12 '16 at 12:32
  • That is exactly what `killall` does. As long as this is the only instance of npm running, one should be fine. – Jonathan Wheeler Dec 12 '16 at 13:03

3 Answers3

5

The PID of the last started background process is stored in $!, so pick it up after starting npm and kill it when needed:

npm start &
npm_pid=$!
...
kill $npm_pid
choroba
  • 231,213
  • 25
  • 204
  • 289
1

You might consider running the process in a screen.

screen -dmS npm npm start #Starts a detached screen named npm, and runs "npm start" inside

Later, when you need to kill the process, you can just kill the screen. When the screen dies, it will take it's child processes with it.

screen -X -S npm quit
Guest
  • 124
  • 7
-1

Perhaps a duplicate of this solution

ps -ef | grep your_process_name | grep -v grep | awk '{print $2}' | xargs kill)
Community
  • 1
  • 1
Jonathan Wheeler
  • 2,539
  • 1
  • 19
  • 29