Ruby仅执行第一行?

Ped*_*mer 4 ruby shell exec

我正在编写一个ruby脚本,发现了这种奇怪的行为。

使用 ruby 2.4.2 [x86_64-darwin16]

基本上,我试图回显两个分开的消息,在index.rb文件中我得到了:

exec("echo 'teste'")
exec("echo 'teste2'")
Run Code Online (Sandbox Code Playgroud)

但是当我跑步时 ruby ./index.rb

输出为:

teste
Run Code Online (Sandbox Code Playgroud)

为什么会这样呢?

这不是输出吗?

testeteste2
Run Code Online (Sandbox Code Playgroud)

mrz*_*asa 7

exec([env,] command... [,options])

通过运行给定的外部命令docs替换当前进程

这意味着第一次调用将exec用替换您的ruby程序echo,因此不执行其余ruby程序。

您可以使用反引号运行所需的命令:

`echo 'teste'`
`echo 'teste2'`
Run Code Online (Sandbox Code Playgroud)

  • ...但是,如果您确实想进行外部系统调用,而不是实际编写ruby,则可能是在寻找[`system`或`Open3`](/sf/answers/417957361/ )而不是`exec`。 (3认同)
  • 需要注意的是,虽然反引号有效,但它们实际上并不理想,因为您对shell解释参数的方式几乎没有控制权。正如Tom所指出的那样,system()和Open3给予了更多控制和保证,例如文件名中的空格不会引起混乱。 (2认同)