How to kill a process by port in Mac OS

Sometimes I leave processes running which take up ports on my local machine (e.g., Redis server). I won’t be able to use the port until it’s freed up, but it’s sometimes a chore to figure out how to kill the process by port.

I found the following snippet super useful to kill a process by port in Mac OS:

Just replace the [port] above with the actual numbered port (e.g., 6379).