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

1 Answer 1

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'`
Sign up to request clarification or add additional context in comments.

7 Comments

makes sense, there's a way to go back to the original script?
nope, you can't go back, you need to use another way of calling a system command
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.
...But if you really do want to make external system calls, rather than actually writing ruby, you're probably looking for system or Open3 instead of exec.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.