Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (terminal) cd in folder from ruby script

Tags:

ruby

I'd like to know if it's possible to change the current terminal directory from where I'm executing my ruby script.

For example, if I'm executing the script from $HOME in the terminal, I would like to cd in $HOME/mydir at the end of the script.

I've tried a couple of things, but I'm always finding in the same directorry where the script was started.

Things I've tried:

Dir.chdir( mydir )
%[cd mydir]

They actually do change directory, but only in the thread of the script execution. When the script ends, my current location in the terminal is still the same I was before launching the script.

I've found something similar in SO, but it's Python-related and response seems negative.


You may ask why?

I'm currently involved in a command line application (using gli) which, as starting point, needs a project folder. So my first command looks like:

$ myfoo new project

Which creates a new folder with name project in the current directory. Now to be able to work with the other commands I need to:

$ cd project
project$ myfoo domore

So I was simply thinking that it would be nice to found my self in project after having executed myfoo new project.


As I was afraid, it's not that easy (not possible at all). So what about using a bash script which does the ruby calls that I want, in place of the standard file generated by RubyGems? Is that feasible? Am I foolish? Should I use eval?


Thanks for the answers. But I'm afraid that no one is acceptable. Probably the question wasn't :).

like image 993
Emiliano Poggi Avatar asked May 25 '11 22:05

Emiliano Poggi


1 Answers

This isn't possible, to my knowledge, since they're different processes. If you need to affect the Ruby script's parent process (Bash), Bash will need to source something. So you could have your Ruby script output some bash commands, then have a Bash wrapper that source's Ruby's output.

Try this as an example, in Bash:

`ruby -e 'puts "cd /tmp"'` | source /dev/stdin

But this will only work in Bash 4.0.

EDIT:

Actually, you can do this with eval instead of source in Bash 3:

eval $(ruby -e'puts "cd /tmp"')
like image 182
Ian Avatar answered Nov 12 '22 12:11

Ian