Ruby run command in a specific directory

I know how to run a shell command in Ruby, for example:

%x[#{cmd}] 

But how to specify the directory to run this command?

Is there a similar workaround similar to subprocess.Popen in Python:

 subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local') 

Thank!

+43
ruby shell command
Apr 13 2018-12-12T00:
source share
6 answers

You can use the block version of Dir.chdir . Inside the block, you are in the requested directory, after the block is still in the previous directory:

 Dir.chdir('mydir'){ %x[#{cmd}] } 
+105
Apr 13 2018-12-12T00:
source share

Ruby 1.9.3 (blocking call):

 require 'open3' Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t| p o.read.chomp #=> "/" } Dir.pwd #=> "/home/abe" 
+10
Apr 13 '12 at 20:45
source share

also taking the shell route

 %x[cd #{dir} && #{cmd}] 
+4
Apr 14 2018-12-12T00:
source share

This may not be the best solution, but try using Dir.pwd to get the current directory and save it somewhere. After that, use Dir.chdir (destination), where destination is the directory from which you want to run your command. After running the command, use Dir.chdir again, using the previously saved directory to restore it.

+1
Apr 13 2018-12-12T00:
source share

I had the same problem and it was solved by putting both teams in reverse ticks and splitting into "& &":

 `cd \desired\directory && command` 
+1
Dec 03 '13 at 17:21
source share

The closest I can see to backtricks with a secure capture2 directive, capture2 :

 require 'open3' output, status = Open3.capture2('pwd', :chdir=>"/tmp") 

In ruby ​​documents you can see other useful Open3 methods. One of the drawbacks is that jruby support for open3 pretty broken.

+1
Aug 26 '14 at 8:10
source share



All Articles