2011-11-16 185 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