DEV Community

Eric Berry
Eric Berry

Posted on

Ruby Scripting: Kill Process by Port

Example

Usage

killports [PORT1] [PORT2] ...

Example: killports 3000 5000

Code

#!/Users/eberry/.asdf/shims/ruby

# See https://www.devdungeon.com/content/enhanced-shell-scripting-ruby

require "amazing_print"

def echo_success(message, port, pid=nil)
  puts [
    "👍🏻",
    port.to_s.yellow,
    pid.nil? ? nil : pid.to_s.cyan,
    message.to_s.white
  ].compact.join(" ")
end

def echo_failed(message, port, pid=nil)
  puts [
    "👎🏻",
    port.to_s.yellow,
    pid.nil? ? nil : pid.to_s.cyan,
    message.to_s.red
  ].compact.join(" ")
end

ARGV.each { |arg|
  port = arg.chomp
  pid = `lsof -t -i tcp:#{port}`.chomp
  if pid.to_i > 0
    _result = `sudo kill #{pid}`

    if $?.success?
      echo_success("killed", port, pid)
    else
      echo_failed("no such process", port, pid)
    end
  else
    echo_success("was not in use", port)
  end
}

if ARGV.empty?
  puts "Usage: ".yellow + "killports [PORT1] [PORT2] ..."
end

exit(0)
Enter fullscreen mode Exit fullscreen mode

Latest comments (0)