Skip to content

Instantly share code, notes, and snippets.

@maxswjeon
Created May 26, 2023 05:07
Show Gist options
  • Select an option

  • Save maxswjeon/f12fd09c7111c198a3fdce1445eb4ce6 to your computer and use it in GitHub Desktop.

Select an option

Save maxswjeon/f12fd09c7111c198a3fdce1445eb4ce6 to your computer and use it in GitHub Desktop.
`kp` - Kill process by Port
#!/bin/bash
if [ $# -ne 1 ]; then
echo "usage: kp [port]"
exit 1
fi
NODE_PID=$(ss -lptn "sport = :$1" | grep -o 'pid=[0-9]\+' | cut -d '=' -f 2)
if [ -z $NODE_PID ]; then
echo "No process using $1 Found"
exit 0
fi
LAST1_PID=$NODE_PID
LAST2_PID=
while true; do
PARENT_INFO=$(ps -o ppid=,cmd= -p $LAST1_PID | xargs)
PARENT_PID=$(echo "$PARENT_INFO" | cut -d ' ' -f 1)
PARENT_CMD=$(echo "$PARENT_INFO" | cut -d ' ' -f 2-)
echo "Found parent process $PARENT_PID with command $PARENT_CMD"
if echo "$PARENT_CMD" | grep sh > /dev/null; then
echo "Found shell process, killing the grandchild ($LAST2_PID)"
kill $LAST2_PID
exit 0
else
LAST2_PID=$LAST1_PID
LAST1_PID=$PARENT_PID
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment