Ruby run shell command in a specific directory

后端 未结 6 1351
死守一世寂寞
死守一世寂寞 2020-12-01 07:23

I know how to run a shell command in Ruby like:

%x[#{cmd}]

But, how do I specify a directory to run this command?

Is there a simila

相关标签:
6条回答
  • 2020-12-01 07:46

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

    Dir.chdir('mydir'){
      %x[#{cmd}]
    }
    
    0 讨论(0)
  • 2020-12-01 07:49

    also, taking the shell route

    %x[cd #{dir} && #{cmd}]
    
    0 讨论(0)
  • 2020-12-01 07:54

    Ruby 1.9.3 (blocking call):

    require 'open3'
    Open3.popen3("pwd", :chdir=>"/") {|i,o,e,t|
      p o.read.chomp #=> "/"
    }
    
    Dir.pwd #=> "/home/abe"
    
    0 讨论(0)
  • 2020-12-01 07:58

    The closest I see to backtricks with safe changing dir is capture2:

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

    You can see other useful Open3 methods in ruby docs. One drawback is that jruby support for open3 is rather broken.

    0 讨论(0)
  • 2020-12-01 07:58

    I had this same problem and solved it by putting both commands in back ticks and separating with '&&':

    `cd \desired\directory && command`
    
    0 讨论(0)
  • 2020-12-01 07:59

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

    0 讨论(0)
提交回复
热议问题