Ava
Ava

Reputation: 6053

How do I run Unix commands using system and backticks?

This works:

system("ruby #{File.dirname(__FILE__) + '/Test')}")

but this

`ruby #{File.dirname(__FILE__) + '/Test'}`

does not run the script Test

And this:

system("ruby #{File.dirname(__FILE__) + '/Test #{arg}'")

does not take the arg value.

What am I doing wrong?

Upvotes: 0

Views: 236

Answers (1)

the Tin Man
the Tin Man

Reputation: 160611

The second doesn't work because there's a unbalanced trailing double-quote (") and closing parenthesis ()) which is probably raising and error, but you're not seeing it because the back-ticks ignore STDERR:

`ruby #{File.dirname(__FILE__) + '/Test'")}`

The third one doesn't work because you're trying to interpolate a variable into a fixed string enclosed in single-quotes, which is also missing a terminating }:

system("ruby #{File.dirname(__FILE__) + '/Test #{arg}'")

You'd see this stand out if you didn't embed the string calculation in your string interpolation:

cmd_file = File.dirname(__FILE__) + '/Test #{arg}'
system("ruby #{ cmd_file }")

Fixing the quoting and using the intrinsic File.join for correctness:

cmd_file = File.join(File.dirname(__FILE__), "Test #{arg}")
system("ruby #{ cmd_file }")

Upvotes: 3

Related Questions