Let's say I have some terminal commands like:
sudo mycommand1
mycommand2
#.....
What should I do run them via ruby script (not bash) in Ubuntu?
UPDATE: I have a ruby script:
def my_method1()
#calculating something.....
end
def method2(var1, var2)
#how do I sudo mycommand1 and any other Lunix command from here?
end
def method3(var4)
#calculating something2....
end
4 Answers 4
You can do system
, exec
, or place the command in backticks.
exec("mycommand")
will replace the current process so that's really only pratical at the end of your ruby script.
system("mycommand")
will create a new process and return true if the command succeeded and nil otherwise.
If you need to use the output of your command in your Ruby script use backticks:
response = 'mycommand`
-
"If you need to use the output of your command in your Ruby script use backticks", or
IO.popen
orOpen3
.the Tin Man– the Tin Man2012年10月30日 05:25:02 +00:00Commented Oct 30, 2012 at 5:25
There are many questions on SO that answer this. However you can run a command in many ways using system
, exec
, (backticks), %x{}
or using open3
. I prefer to use open3 -
require 'open3'
log = File.new("#{your_log_dir}/script.log", "w+")
command = "ls -altr ${HOME}"
Open3.popen3(command) do |stdin, stdout, stderr|
log.puts "[OUTPUT]:\n#{stdout.read}\n"
unless (err = stderr.read).empty? then
log.puts "[ERROR]:\n#{err}\n"
end
end
If you want to know more about other options you can refer to Ruby, Difference between exec, system and %x() or Backticks for links to relevant documentation.
-
That is a good link, I used it as a reference to make a direct answer. (I'm just letting you know)yeyo– yeyo2012年10月30日 07:06:28 +00:00Commented Oct 30, 2012 at 7:06
You can try these approaches:
%x[command]
Kernel.system"command"
run "command"
make some file.rb
with:
#!/path/to/ruby
system %{sudo mycommand1}
system %{mycommand2}
and the chmod
the file with exec permissions (e.g. 755)
It you need to pass variables between the two commands, run them together:
system %{sudo mycommand1; \
mycommand2}
-
it can contain another ruby code. I mean: how can I do that in Ruby script?Alexandre– Alexandre2012年10月30日 04:45:49 +00:00Commented Oct 30, 2012 at 4:45
exec('ls ~')
my_method
,method2
, ormethod3
from the command line - and then those commands call other shell commands?