-
-
Save maxswjeon/f12fd09c7111c198a3fdce1445eb4ce6 to your computer and use it in GitHub Desktop.
`kp` - Kill process by Port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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