这个解释是基于我一个朋友的 comments .如果你想改进脚本,请随时在链接中更新它.
首先,请注意,当Ruby调用shell时,它通常会调用/bin/sh
not Bash.并非所有系统上的/bin/sh
都支持某些Bash语法.
以下是执行shell脚本的方法:
cmd = "echo 'hi'" # Sample string that can be used
Kernel#`
,通常称为backticks–`cmd`
这与许多其他语言一样,包括Bash、PHP和Perl.
返回shell命令的结果(即标准输出).
doctor :http://ruby-doc.org/core/Kernel.html#method-i-60
value = `echo 'hi'`
value = `#{cmd}`
内置语法,%x( cmd )
x
个字符后是分隔符,可以是任何字符.
返回shell命令的结果(即标准输出),就像backticks一样.
doctor :https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-Percent+Strings
value = %x( echo 'hi' )
value = %x[ #{cmd} ]
Kernel#system
在子shell中执行给定的命令.
如果找到并成功运行该命令,则返回true
,否则返回false
.
doctor :http://ruby-doc.org/core/Kernel.html#method-i-system
wasGood = system( "echo 'hi'" )
wasGood = system( cmd )
Kernel#exec
通过运行给定的外部命令替换当前进程.
返回none,当前进程将被替换,并且永远不会继续.
doctor :http://ruby-doc.org/core/Kernel.html#method-i-exec
exec( "echo 'hi'" )
exec( cmd ) # Note: this will never be reached because of the line above
这里有一些额外的建议:
$?.exitstatus
更多阅读请参见: