Joseph Mastey Joseph Mastey - 14 days ago 10
Ruby Question

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

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