Finding Binaries with Ruby

Here’s a quick one liner in ruby that finds all of the binaries on your PATH:

  Dir[*ENV['PATH'].split(':').map{|p| p+"/*"}].select{|f| File.executable? f}.map{|f| File.basename f}.uniq

How does it work?

Working in the order of execution, we get the PATH from your environment variables. Next we split by : the path separator, and then add "/*" to it. This gives you an array of strings like /usr/bin/*. Passing those into Dir[ ] will get you all the files matching those paths. From there we select all files that are executable, use File.basename to get the filename from the path, and then call uniq to make sure we don’t have any duplicates.

This might not be something you do every day, but it does show off a number of ruby’s File and Enumerable methods.


1 Comment

Filed under ruby

One response to “Finding Binaries with Ruby

  1. Pingback: Getting to Know the Ruby Standard Library – Abbrev | End of Line