DEV Community

Eric Berry
Eric Berry

Posted on

5 1

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more