views:

385

answers:

2

I'm trying to change the directory of the shell I start the ruby script form via the ruby script itself...

My point is to build a little program to manage favorites directories and easily change among them.

Here's what I did

#!/usr/bin/ruby
Dir.chdir("/Users/luca/mydir")

and than tried executing it in many ways...

my_script (this doesn't change the directory)
. my_script (this is interpreted as bash)
. $(ruby my_script) (this is interpreted as bash too!)

any idea?

A: 
#!/usr/bin/env ruby

`../your_script`

Like this?

Or start your script in the directory you want it to do something.

Maybe I don't get your question. Provide some more details.

daddz
+3  A: 

Cannot be done. Child processes cannot modify their parents environment (including the current working directory of the parent). The . (also known as source) trick only works with shell scripts because you are telling the shell to run that code in the current process (rather than spawning a subprocess to run it). Just for fun try putting exit in a file you run this way (spoiler: you will get logged out).

If you wish to have the illusion of this working you need to create shell functions that call your Ruby script and have the shell function do the actual cd. Since the functions run in the current process, they can change the directory. For instance, given this ruby script (named temp.rb):

#!/usr/bin/ruby

print "/tmp";

You could write this BASH function (in, say, you ~/.profile):

function gotmp {
    cd $(~/bin/temp.rb)
}

And then you could say gotmp at the commandline and have the directory be changed.

Chas. Owens
very interesting... I'll work on it..by the way, do you know of any command line utility to better manage navigation, favorites etc (not a full file manager like mc)?thanks
luca
Tab completion rules out most of the need for "favorites", you may also want to look at symbolic links (ln -s /tmp ~/tmp). You may also want to look into pushd and popd as alternatives to cd.
Chas. Owens
Chas, sorry to solicit, but could you look at this question http://stackoverflow.com/questions/1151217 and see if you can shed any light on it, please? Thanks muchly.
Yar