tags:

views:

61

answers:

4

I'd like to change the pwd of the current shell from within a ruby script. So:

> pwd
/tmp
> ruby cdscript.rb
> pwd
/usr/bin

This is the code I have right now:

exec('cd /usr/bin')

Unfortunately, cd is a builtin command. So:

`exec': No such file or directory - cd (Errno:ENOENT)

Any workaround for this?


No way to get it working in ruby itself, so I switched gears. I modified the script to output the target directory path and then defined a function in .bashrc that would pass the arguments through the script and then cd to the right directory. Not self-contained as I would have hoped, but it did the job.

Thanks for the replies, folks.

+1  A: 

Dir.chdir("/usr/bin") will change the pwd within the ruby script, but that won't change the shell's PWD as the script is executed in a child process.

Vinko Vrsalovic
Which wasn't the question.
sepp2k
Depends on how you look at it, he was having a problem trying to exec() 'cd', which will (also) never work. If he had asked about why Dir.chdir() wasn't working then this answer would have been totally irrelevant. Anyway, edited for completeness.
Vinko Vrsalovic
+5  A: 

You won't be able to change the working directory of your shell.

When it executes ruby, it forks so you get a new environment, with a new working directory.

Bertrand Marron
A: 

You can't change the working directory (or the environment variables for that matter) of the shell that invoked you in a ruby script (or any other kind of application). The only commands that can change the pwd of the current shell are shell built-ins.

sepp2k
+1  A: 

As other answers already pointed out, you can change the pwd inside your ruby script, but it only affects the child process (your ruby script). A parent process' pwd cannot be changed from a child process.

One workaround could be, to have the script output the shell command(s) to execute and call it in backticks (i.e. the shell executes the script and takes its output as commands to execute)

myscript.rb:

# … fancy code to build somepath …
puts "cd #{somepath}"

to call it:

`ruby myscript.rb`

make it a simple command by using an alias:

alias myscript='`ruby /path/to/myscript.rb`'

Unfortunately, this way you can't have your script output text to the user since any text the script outputs is executed by the shell (though there are more workarounds to this as well).

Andreas