Skip to content

Instantly share code, notes, and snippets.

@m5r
Created February 21, 2018 11:15
Show Gist options
  • Save m5r/0eb4dd251d719f670f341768e6b06ec7 to your computer and use it in GitHub Desktop.
Save m5r/0eb4dd251d719f670f341768e6b06ec7 to your computer and use it in GitHub Desktop.

Revisions

  1. m5r created this gist Feb 21, 2018.
    21 changes: 21 additions & 0 deletions destroyByPort.sh
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,21 @@
    #!/bin/bash
    if [ -z "$1" ]; then
    echo "Error: No argument passed" >&2; exit 1
    fi

    if ! [[ $1 =~ ^[0-9]+$ ]] ; then
    echo "Error: Argument is not a number" >&2; exit 1
    fi

    PIDToKill=$(lsof -i:$1 | grep LISTEN | awk '{print $2}' | uniq)

    if [ -z "$PIDToKill" ]; then
    echo "Error: No process listening on port ${1} found" >&2; exit 1
    fi

    {
    kill -9 $PIDToKill
    echo "Successfully killed process with PID ${PIDToKill} listening on port ${1}"; exit 1
    } || {
    echo "Error: unknown error when tried to kill process ${PIDToKill}" >&2; exit 1
    }