TAGS :Viewed: 9 - Published at: a few seconds ago

[ exec the cd command in a ruby script ]

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.

Answer 1


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.

Answer 2


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.

Answer 3


Stumbled across this while searching to do the same thing.

I was able to solve this by running multiple statements within the backticks.

'cd #{path} && <statement> && cd ..'

Answer 4


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).

Answer 5


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.