0

I use a bash script to run both the frontend and the backend of my full-stack application on macOS:

#!/usr/bin/env bash

export PORT="3001"
export API_PORT="5001"
export MAIN_URL="http://localhost:"

cd Client
npm run dev &
cd ..
nodemon index.js &

The issue is that I want to kill the PID listening to the port before I execute the npm and nodemon commands. Is there a way I can get the specific PID? Can I write the listening PID to a .pid file and then read from it when I want to kill?

TheMachineX
  • 179
  • 1
  • 11

1 Answers1

1

Try this:

pid=$(sudo lsof -i :3001 -t)
kill $pid
  • 1
    this works! thanks (no need for the sudo) – TheMachineX Nov 02 '21 at 06:41
  • 1
    You want to avoid the [useless `grep`](https://www.iki.fi/era/unix/award.html#grep); you can refactor to just `sudo lsof -i :3001 -F | sed -n 's/^p//p'` ... but of course with `lsof -t` you don't need the pipe at all. – tripleee Nov 04 '21 at 08:05