Last active
November 5, 2025 06:09
-
-
Save dropocol/bc1bb15b766c5367b20064c638f09cd4 to your computer and use it in GitHub Desktop.
Code snippet to kill process
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
| # Process management | |
| k() { | |
| if [ -z "$1" ]; then | |
| echo "Usage: k <port> # Kill single port" | |
| echo " k <port1,port2> # Kill multiple ports" | |
| echo " k <start-end> # Kill port range" | |
| echo "Examples:" | |
| echo " k 3000 # Kill port 3000" | |
| echo " k 3000,3001 # Kill ports 3000 and 3001" | |
| echo " k 3000-3005 # Kill ports 3000 through 3005" | |
| return 1 | |
| fi | |
| local input="$1" | |
| local ports_to_kill=() | |
| # Handle comma-separated ports | |
| if [[ "$input" == *","* ]]; then | |
| # Simple approach: loop through comma-separated values | |
| local input_copy="$input" | |
| while [[ "$input_copy" == *","* ]]; do | |
| local port="${input_copy%%,*}" | |
| input_copy="${input_copy#*,}" | |
| ports_to_kill+=("$port") | |
| done | |
| # Add the last port | |
| ports_to_kill+=("$input_copy") | |
| # Handle port ranges | |
| elif [[ "$input" == *"-"* ]]; then | |
| IFS='-' read start end <<< "$input" | |
| if [[ "$start" =~ ^[0-9]+$ ]] && [[ "$end" =~ ^[0-9]+$ ]] && [ "$start" -le "$end" ]; then | |
| for ((port=start; port<=end; port++)); do | |
| ports_to_kill+=("$port") | |
| done | |
| else | |
| echo "❌ Invalid range format. Use: k <start-end> (e.g., k 3000-3005)" | |
| return 1 | |
| fi | |
| # Handle single port | |
| else | |
| if [[ "$input" =~ ^[0-9]+$ ]]; then | |
| ports_to_kill+=("$input") | |
| else | |
| echo "❌ Invalid port number. Use: k <port> (e.g., k 3000)" | |
| return 1 | |
| fi | |
| fi | |
| # Kill processes on all specified ports | |
| local killed_count=0 | |
| for port in "${ports_to_kill[@]}"; do | |
| local pids=$(lsof -ti :$port 2>/dev/null) | |
| if [ -n "$pids" ]; then | |
| echo "🔪 Killing process(es) on port $port: $pids" | |
| echo "$pids" | xargs kill -9 2>/dev/null || true | |
| ((killed_count++)) | |
| else | |
| echo "✅ No process found on port $port" | |
| fi | |
| done | |
| if [ "$killed_count" -gt 0 ]; then | |
| echo "🎯 Killed processes on $killed_count port(s)" | |
| else | |
| echo "ℹ️ No processes to kill" | |
| fi | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment