2

I realize that:

Dir.chdir("/path/to/some/dir/")

will temporarily change to the appropriate directory. My question is: is there any way to make this persistent? When I exist the script, I remain in the same directory as I started. I have also tried execute commands with backticks, but it seems like everything is run in a new shell.

Does Ruby have the ability to change my shell's directory?

Jordan Scales
  • 2,687
  • 4
  • 28
  • 37
  • 5
    No. You can't change the state of the parent's environment, including current working directory, environment variables, or what have you. This is true for all programs including shell scripts (with exclusion of ones that are "dotted" in, since those are executed inline), perl, python, C programs, Java etc etc etc. – PaulProgrammer Sep 23 '13 at 21:28

2 Answers2

5

No, it is not possible.

In fact, no child process can change the current working directory of its parent process.

When you execute a script (or any program) from your command shell you are actually doing a "fork/exec" pair, which means you create a "child process" which is separate from your shell "parent process" in many ways. The child can make changes to its own environment but cannot (typically) change the parent environment.

maerics
  • 151,642
  • 46
  • 269
  • 291
1

One small correction:

Dir.chdir("/path/to/some/dir/")

changes the directory for the rest of the script execution. A temporary change is possible with the block version of the command.


And to answer your question: No, it is not possible.

Even the following script does not work:

puts Dir.pwd
puts `cd ..`
puts Dir.pwd

The cd-command in backticks starts a new environment, so your parent's shell will not change the directory.

Community
  • 1
  • 1
knut
  • 27,320
  • 6
  • 84
  • 112