4

I'm writing a ruby script and found this strange behaviour.

Using ruby 2.4.2 [x86_64-darwin16]

Basically I'm trying to echo two separated messages and in my index.rb file I got:

exec("echo 'teste'")
exec("echo 'teste2'")

But when I run ruby ./index.rb

The output is:

teste

Why that's happening?

Shouldn't this be the output?

testeteste2
mrzasa
  • 22,895
  • 11
  • 56
  • 94
Pedro Sturmer
  • 547
  • 6
  • 20

1 Answers1

7

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

Replaces the current process by running the given external command docs

It means that the first call to exec replaces your ruby program with echo, so the rest of the ruby program is not executed.

You can use backticks to run a command like you want:

`echo 'teste'`
`echo 'teste2'`
mrzasa
  • 22,895
  • 11
  • 56
  • 94
  • makes sense, there's a way to go back to the original script? – Pedro Sturmer Aug 29 '19 at 14:51
  • nope, you can't go back, you need to use another way of calling a system command – mrzasa Aug 29 '19 at 14:53
  • 1
    Is there a good reason why you need to call `exec`, at all? One would normally use `puts` or `print` to output text to STDOUT, rather than making an external call. – Tom Lord Aug 29 '19 at 15:02
  • acually I'm dealing with shell scripts, for writing files and packing things – Pedro Sturmer Aug 29 '19 at 15:04
  • @PedroSturmer Again -- The normal way to do all of this (*in ruby*) is to [write the file with ruby](https://www.rubydoc.info/github/rubyworks/facets/File.write), not external shell scripts. Of course there are exceptions to the rule, but I cannot advise without more context. – Tom Lord Aug 29 '19 at 15:21
  • 3
    ...But if you really do want to make external system calls, rather than actually writing ruby, you're probably looking for [`system` or `Open3`](https://stackoverflow.com/a/5970819/1954610) instead of `exec`. – Tom Lord Aug 29 '19 at 15:22
  • 2
    As a note, while backticks work, they're really far from ideal as you have very little control over how the shell interprets the arguments. `system()` and as Tom points out `Open3` give way more control and assurances that things like spaces in filenames won't cause chaos. – tadman Aug 29 '19 at 16:06