Search code examples
bashmacosreact-fullstack

Finding the PID listening to a port


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?


Solution

  • Try this:

    pid=$(sudo lsof -i :3001 -t)
    kill $pid