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?
Cannot be done. Child processes cannot modify their parents environment (including the current working directory of the parent). The
.(also known assource) 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 puttingexitin 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):You could write this BASH function (in, say, you
~/.profile):And then you could say
gotmpat the commandline and have the directory be changed.