ruby用变量执行bash命令

时间:2011-11-16 21:31:34

标签: ruby bash command

我需要在Ruby脚本中执行Bash命令。根据{{​​3}}和其他一些谷歌来源,大约有6种方法可以做到这一点。

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 

2 个答案:

答案 0 :(得分:6)

对于它的价值你可以实际链接这些方法,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

答案 1 :(得分: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\""