Created
February 3, 2026 19:43
-
-
Save Swader/4a1f1724adcde5828a6736e215a0f763 to your computer and use it in GitHub Desktop.
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
| function kill() { | |
| emulate -L zsh | |
| setopt extendedglob | |
| if (( $# == 0 )); then | |
| builtin kill | |
| return | |
| fi | |
| local is_signal=0 all_numeric=1 arg | |
| for arg in "$@"; do | |
| [[ "$arg" == -* || "$arg" == SIG* ]] && is_signal=1 | |
| [[ "$arg" == <-> ]] || all_numeric=0 | |
| done | |
| if (( is_signal || all_numeric )); then | |
| builtin kill "$@" | |
| return | |
| fi | |
| local target="$*" | |
| if [[ "$target" == :* ]]; then | |
| local port="${target#:}" | |
| if ! [[ "$port" == <-> ]]; then | |
| print -u2 "kill: invalid port: $port" | |
| return 1 | |
| fi | |
| local -a pids pids_udp | |
| pids=($(lsof -n -P -t -iTCP:$port -sTCP:LISTEN 2>/dev/null)) | |
| pids_udp=($(lsof -n -P -t -iUDP:$port 2>/dev/null)) | |
| local p | |
| for p in $pids_udp; do | |
| if [[ -z ${pids[(r)$p]} ]]; then | |
| pids+=$p | |
| fi | |
| done | |
| if (( ${#pids} == 0 )); then | |
| echo "No processes found listening on port $port." | |
| return 1 | |
| fi | |
| local pidlist="${(j:,:)pids}" | |
| echo "Processes on port $port:" | |
| ps -o pid,ppid,user,%cpu,%mem,etime,state,command -p $pidlist | |
| read -q "REPLY?Kill these ${#pids} process(es)? [y/N] " | |
| echo | |
| if [[ $REPLY == [Yy] ]]; then | |
| builtin kill "${pids[@]}" && echo "Sent SIGTERM to ${#pids} process(es)." | |
| else | |
| echo "Cancelled." | |
| fi | |
| else | |
| local pattern="$target" | |
| local -a pids | |
| pids=($(pgrep -fi "$pattern" 2>/dev/null)) | |
| if (( ${#pids} == 0 )); then | |
| echo "No processes found matching \"$pattern\"." | |
| return 1 | |
| fi | |
| local pidlist="${(j:,:)pids}" | |
| echo "Matches for \"$pattern\":" | |
| ps -o pid,ppid,user,%cpu,%mem,etime,state,command -p $pidlist | |
| read -q "REPLY?Kill these ${#pids} process(es)? [y/N] " | |
| echo | |
| if [[ $REPLY == [Yy] ]]; then | |
| builtin kill "${pids[@]}" && echo "Sent SIGTERM to ${#pids} process(es)." | |
| else | |
| echo "Cancelled." | |
| fi | |
| fi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment