I noticed when playing a game (League of Legends) that certain processes hang and won’t let me launch the game properly.

I usually have to kill the process and reboot it to get the game to work properly.

That’s simple enough. I just have to do the following:

  1. Run ps aux to see what all the running processes are
  2. Realize there’s too many to easily read through and run:
    • ps aux | grep -i league to find all the processes with the word league in them
  3. Go through each PID in that list and run kill <PID>

I did this so many times that I decided to turn it into a little script:

#!/usr/bin/env ruby

# Command Structure:
# kill_all <string_to_match>

def find_processes(string)
  `ps aux | grep -i #{string}`.split("\n")
end

def get_process_id(process)
  process.split.map(&:strip)[1]
end

def get_process_command(process)
  pieces = process.split.map(&:strip)
  pieces[10..-1].join(' ')
end


def kill_all_found_processes!(processes)
  processes.each do |process|
    id = get_process_id(process)
    command = get_process_command(process)

    puts "\033[96mKilling Process(#{id}) which was running:\033[0m \n\t#{command}\n"
    `kill -9 #{id}`
  end
end

string_to_match = ARGV[0]
if string_to_match.nil? || string_to_match.empty?
  puts "\033[91mMissing string to match.\nExpected: kill_all <string_to_match>\033[0m"
  exit(-1) # Exit with a non-zero code to signify an error occurred
end


processes = find_processes(string_to_match)
kill_all_found_processes!(processes)

Adding to PATH and omitting the ‘.rb’ extension

I added the script to my PATH so that I can call the script from anywhere without having to type out the full path:

# ~/.zshrc
export PATH="~/path/to/kill_all:$PATH"

You may have noticed that even though this is a Ruby script, I don’t have the .rb file extension and I’m not executing the script with the Ruby executable like you would normally with Ruby scripts:

ruby kill_all.rb league

That’s because of the first line in the script:

#!/usr/bin/env ruby

This tells the OS to treat this file as a Ruby executable.