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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

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