A script for terminating a server on a certain port:
#!/bin/bash
PORT="$1"
SIGNAL="$2"
if [ "${SIGNAL}" != "" ]; then SIGNAL=" -${SIGNAL}"; fi
lsof -i:"${PORT}" |\
grep -e "localhost:${PORT}" -e TCP -e LISTEN |\
tr -s ' ' |\
cut -d' ' -f2 |\
tee /dev/tty |\
xargs --no-run-if-empty kill "$SIGNAL"
Works: killbyport 4242
But if I want to do a kill -9 I'd do: killbyport 4242 9,
and that errors:
kill: (-9): No such process
The xargs and kill aren't cooperating – how do I fix it?
(PS: I want to fix this script, rather than change it to something else. It's almost working.)