Skip to content

Instantly share code, notes, and snippets.

@mtarbit
Last active October 10, 2016 13:14
Show Gist options
  • Save mtarbit/3344424ff8231f8bad0d to your computer and use it in GitHub Desktop.
Save mtarbit/3344424ff8231f8bad0d to your computer and use it in GitHub Desktop.
A bash function wrapper for lsof to find any listening processes.
listening() {
if [ -z "$1" ]; then
lines=$(lsof -P -s TCP:LISTEN -i TCP | tail -n +2)
pairs=$(echo -n "$lines" | awk '{split($9,a,":"); print $2":"a[2]}' | uniq)
format_string="%5s %5s %s\n"
if [ -n "$pairs" ]; then
printf "$format_string" "PORT" "PID" "COMMAND"
for pair in $pairs; do
port="${pair/#*:}"
proc="${pair/%:*}"
cmnd="$(ps -p "$proc" -o command=)"
printf "$format_string" "$port" "$proc" "${cmnd:0:$COLUMNS-12}"
done
fi
else
pid=$(lsof -P -s TCP:LISTEN -i TCP:"$1" -t | uniq)
if [ -n "$pid" ]; then
ps -p "$pid" -o pid,command
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment