Running Linux system commands from Ruby script
I have the following Ruby script that creates a Debian package, which works fine:
#!/usr/bin/ruby dest = "#{File.dirname(__FILE__)}/../build" package = "foo" [ "cd #{dest} && tar czvf data.tar.gz bin console data.sql etc filter install.rb", "cd #{dest} && tar czvf control.tar.gz control", "cd #{dest} && echo 2.0 > debian-binary", "cd #{dest} && ar -cr #{packa开发者_Python百科ge}.deb debian-binary control.tar.gz data.tar.gz", "cd #{dest} && mv #{package}.deb ..", "cd #{dest} && rm data.tar.gz control.tar.gz", ].each do |command| puts command system(command) end
Is there a way in Ruby where I can leave off the "cd #{dest} &&" part of each command?
Dir.chdir(dest) do
# code that shall be executed while in the dest directory
end
Dir.chdir
when invoked with a block will change to the given directory, execute the block and then change back.
You can also use it without a block, in which case it will never change back.
Yes. Use Dir.chdir
:
#!/usr/bin/ruby
dest = "#{File.dirname(__FILE__)}/../build"
package = "foo"
Dir.chdir dest
[
"tar czvf data.tar.gz bin console data.sql etc filter install.rb",
"tar czvf control.tar.gz control",
"echo 2.0 > debian-binary",
"ar -cr #{package}.deb debian-binary control.tar.gz data.tar.gz",
"mv #{package}.deb ..",
"rm data.tar.gz control.tar.gz",
].each do |command|
puts command
system(command)
end
精彩评论