2011-11-16 186 views
7

我需要在Ruby脚本中执行Bash命令。根据"6 Ways to Run Shell Commands in Ruby" by Nate Murray和其他一些Google搜索源,大约有6种方法可以做到这一点。ruby​​使用变量执行bash命令

print "enter myid: " 
myID = gets 
myID = myID.downcase 
myID = myID.chomp 
print "enter host: " 
host = gets 
host = host.downcase 
host = host.chomp 
print "winexe to host: ",host,"\n" 
command = "winexe -U domain\\\\",ID," //",host," \"cmd\"" 
exec command 
+0

你认为'command'是什么类? –

回答

4

对于什么是值得你其实可以连锁的方法,并puts将打印一个换行符你,所以这可能仅仅是:

print "enter myid: " 
myID = STDIN.gets.downcase.chomp 

print "enter host: " 
host = STDIN.gets.downcase.chomp 

puts "winexe to host: #{host}" 
command = "winexe -U dmn1\\\\#{myID} //#{host} \"cmd\"" 
exec command 
+0

完美谢谢。这是我的第一个ruby脚本,所以也要感谢你关于链接这些方法的注意事项,它的一些恶意使用我想的很多。 – toosweetnitemare

+0

如果您不想在带引号的字符串内插入变量,也可以使用字符串连接运算符(+):'command =“winexe -U dmn1 \\\\”+ myId +“//”+ host + '''cmd''',或者使用Ruby的类似printf的语法:'command ='winexe -U dmn1 \\\\%s //%s“cmd”'%[myId,host]' –

+0

谢谢glenn,是非常有用的信息 – toosweetnitemare

5

它看起来像有可能是麻烦你是怎样把你的命令字符串。
另外,我不得不直接引用STDIN。

# Minimal changes to get it working: 
print "enter myid: " 

myID = STDIN.gets 
myID = myID.downcase 
myID = myID.chomp 

print "enter host: " 
host = STDIN.gets 
host = host.downcase 
host = host.chomp 

print "winexe to host: ",host,"\n" 
command = "echo winexe -U dmn1\\\\#{myID} //#{host} \"cmd\"" 
exec command 



紧凑型:

print "enter myid: " 
myID = STDIN.gets.downcase.chomp 

print "enter host: " 
host = STDIN.gets.downcase.chomp 

puts "winexe to host: #{host}" 
exec "echo winexe -U dmn1\\\\#{myID} //#{host} \"cmd\"" 

最后两行用printf类型:

puts "winexe to host: %s" % host 
exec "echo winexe -U dmn1\\\\%s //%s \"cmd\"" % [myID, host] 

最后两行加字符串连接:

puts "winexe to host: " + host 
exec "echo winexe -U dmn1\\\\" + myID + " //" + host + " \"cmd\"" 

最后两行用C++风格的追加:

puts "winexe to host: " << host 
exec "echo winexe -U dmn1\\\\" << myID << " //" << host << " \"cmd\"" 
+0

这也适用,谢谢。但即时通讯将使用马特上面显示的链接方法。 – toosweetnitemare

+0

@toosweetnitemare:出于某种原因,我的想法是我应该尽可能少地改变你的代码,但是现在这似乎是一个坏主意:P –

+0

lol。昨天下午我刚刚教我自己Ruby,然后发布我的问题,所以它肯定表明我对语言的语法缺乏了解。感谢您抽出时间将您的示例分解为许多不同的选项。这对其他用户稍后查看此线程将非常有用。如果我能给出两个答案的功劳,我也会给你。谢谢您的意见! – toosweetnitemare