Search

 


Yeah, right!

Change Current Directory with Ruby script

Posted by Paul McConnon Sat, 27 Oct 2007 10:47:00 GMT

I was searching online for a method to change the current working directory of a Bash session using a ruby script.

Essentially I wanted to write a shortcut script that would take me straight to the directory of whatever Rails application I was working on.

I wanted a script called ‘go’ that I could use like this:

paul@ubuntu:~$ go plopcentral
paul@ubuntu:~/Development/Sites/PlopCentral$

The script would search a few predefined base paths for the folder and then CD to that folder.

I first tried writing in pure Ruby but unfortunately, executing a ruby script that changes the current working directory within the script, loses these changes when the script exits (this is by design and completely correct, a script should not be able to affect it’s parent process)

I came up with a workaround by making the ruby script return the location of the first folder it found and used a Bash function to change to the returned folder.

Now for the script go.rb, store this in your home folder

#!/usr/bin/ruby
# searches PATHS for a folder then cds to that folder
search = ARGV[0] #get search term
PATHS = ['~/Development','~/Documents']
result = nil
PATHS.each {|path|
    result = `ls -R #{path}/ | grep -m1 -i /#{search}`.gsub!(/:$/,'') unless result
}
puts "cd #{result}" if result

This uses the OS’s ls and grep to very quickly find a path with the search term.

This on it’s own is not enough, we need the OS to take that output and use it to change the current directory. To accomplish this we need to define a function in our ~/.bashrc file.

Add the following to the bottom of your ~/.bashrc file.
go()
{
    eval $(~/go.rb $1)
}

This function takes it’s first parameter and passes it to the Ruby script defined before, eval’s it and uses the output (if any) to change working directory of the current Bash session.

New you can jump straight to folders with

go path

where path is a partial part the folder you want to cd to.

This is a very simple use of the method but illustrates how to use ruby with Bash and could be extended so that it uses databases etc.

Imagine Activerecord or more complex Ruby libraries for use in Bash.

Note: For those very familiar with shell programming there are bound to be pure Bash ways to accomplish this. I am more familiar with Ruby and wanted to use it.