Run cd command in ruby ​​script

I want to change the pwd of the current shell from a ruby ​​script. So:

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

This is the code that I have right now:

 exec('cd /usr/bin') 

Unfortunately, cd is a built-in command. So:

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

Any workaround for this?


It is impossible to make it work in ruby, so I switched gear. I modified the script to output the path to the target directory, and then defined a function in .bashrc that will pass the arguments through the script and then cd to the right directory. Not self-sufficient, as I would have hoped, but he did the job.

Thanks for the responses guys.

+4
source share
6 answers

As already mentioned in other answers, you can change pwd inside a ruby ​​script, but this only affects the child process (your ruby ​​script). Unable to modify pwd parent process from child process.

A workaround may be for the script to output shell commands for execution and call them in reverse cycles (i.e., the shell executes the script and takes its output as commands for execution)

myscript.rb:

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

to call him:

 `ruby myscript.rb` 

make it a simple command using an alias:

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

Unfortunately, this way you cannot get the text of the script output to the user, since any script text is displayed by the shell (although there are other workarounds for this).

+3
source

Dir.chdir("/usr/bin") will change the pwd in the ruby ​​script, but it will not change the shell PWD, since the script is executed in the child process.

+12
source

You cannot change the working directory of your shell.

When he does ruby, he forks, so you get a new environment with a new working directory.

+8
source

Stumbled upon this while searching to do the same.

I was able to solve this by running several statements in the opposite direction.

 'cd #{path} && <statement> && cd ..' 
+6
source

You cannot change the working directory (or environment variables, if any) of the shell that called you in the ruby ​​script (or any other kind of application). The only commands that can change the pwd of the current shell are the built-in shells.

0
source

You can use system instead of exec . This works for me.

Like system("cd #{new_path} && <statement> && cd #{original_path}")

0
source

All Articles