Max D. wrote:
I created a script. At some point I should change from whatever
directory I’m currently in (in Terminal) to a certain directory from the
ruby script.
So far I find other solutions that do not satisfy me. The one with which
I managed to change directories in the terminal needs another .sh file.
When launching the .sh script from the terminal, actually changes the
directory (pwd). But if I launch from the ruby script, does not change
the output terminal (pwd).
Then, I want the working directory to be changed (in terminal) by the
Ruby program after it exits.
Any suggestions?
If this is under Unix, then basically it can’t happen.
When you start a ruby interpreter, you are spawning (fork+exec) a new
process. This new process has its own environment, including its own
concept of “current directory”. Any change to current directory in this
new process does not, indeed cannot, affect the current directory in the
parent.
This isn’t a Ruby limitation, but of any spawned process, including
another shell. See what happens when you do this:
cd /tmp
pwd
sh # start a new shell
cd /usr
pwd
exit # exit the new shell, returning control to
parent
pwd # parent working directory unchanged
The ‘cd’ command only works because it is a shell builtin, not an
external command like /bin/cd.
Another test: create a file “chdir.sh” containing the following:
#!/bin/sh
cd /tmp
Make it executable (chmod +x chdir.sh) and run it (./chdir.sh). Nothing
happens; the directory change was in the subshell.
However if you run it as “. chdir.sh” (note the space after the dot) it
is read as a series of instructions into the current shell. The first
line is ignored as a comment, and the second is run as if you had typed
it into the current shell, so it invokes the cd builtin as before.
I’m not sure if you can get a shell to accept commands from its child on
a pipe. I tried
. <(ruby -e ‘puts “cd /tmp”’)
but that doesn’t seem to work, even though
cat <(ruby -e ‘puts “cd /tmp”’)
works as expected.