使用rake sh时如何检索命令的输出?

Chr*_*mbo 18 ruby rake

我正在使用sh运行命令,需要读取该命令的输出.例如

sh"whoami"

但是sh似乎只返回true而不是包含whoami命令输出的字符串.有谁知道解决方案?

khe*_*lll 16

有几种方法:

output = `whoami`

#or

output = %x[whoami]

# or using 'system' but in case of errors it's gonna return false

output = system "whoami"
Run Code Online (Sandbox Code Playgroud)


pri*_*ing 6

只需使用反引号来执行语句:

output = `whoami`
Run Code Online (Sandbox Code Playgroud)

结果将在'output'变量中.