How to call system() with array

Hi,

I’m a new Ruby programmer and I can’t figure this out.

I’d like to do the following in Ruby:

system ("/bin/program arg1 arg2 arg3")

But I don’t want to be exposed to shell injection attack.
I’m looking for something like C lib’s execv().

I’d like to do some like:
myarray = ["/bin/program", “arg1”, “arg2”, “arg3” ]
system (myarray)

I’ve tried many ways, but just can’t figure out. Any help is
highly appreciated.

Thanks!

I’ve tried something like (I worried about Ruby lumping my arg1/2/3 into
1 arg; but turns out it didn’t even get past syntax checker):

system ("/bin/program", “arg1 arg2 arg3”)
but I get a syntax error at the “,” where Ruby expects “)”.

I’ve also tried:

system ( ["/bin/program", “/bin/program”], “arg1 arg2 arg3” )
But got the same syntax error.

frank houser wrote in post #1007708:

I’d like to do some like:
myarray = ["/bin/program", “arg1”, “arg2”, “arg3” ]
system (myarray)

I’ve tried many ways, but just can’t figure out. Any help is
highly appreciated.

You’ll kick yourself:

system(*myarray)

frank houser wrote in post #1007708:

Hi,

I’m a new Ruby programmer and I can’t figure this out.

I’d like to do the following in Ruby:

system ("/bin/program arg1 arg2 arg3")

But I don’t want to be exposed to shell injection attack.
I’m looking for something like C lib’s execv().

I’d like to do some like:
myarray = ["/bin/program", “arg1”, “arg2”, “arg3” ]
system (myarray)

I’ve tried many ways, but just can’t figure out.

The syntax in the docs is:

system("/bin/program", arg1, arg2, arg3)

ruby’s splat operator explodes the array into individual elements,
producing the same method call.

Thanks that works!

frank houser wrote in post #1007715:

I’ve tried something like (I worried about Ruby lumping my arg1/2/3 into
1 arg; but turns out it didn’t even get past syntax checker):

system ("/bin/program", “arg1 arg2 arg3”)
but I get a syntax error at the “,” where Ruby expects “)”.

The problem is that you have put a space before the parentheses.

system("/bin/echo",“hello”) # correct

system ("/bin/echo",“hello”) # warning in ruby 1.8;
# syntax error in ruby 1.9

The reason is that Matz wanted to support this:

puts (-3).abs

which is parsed as

puts((-3).abs)

i.e. the space forces the next opening parenthesis to be part of an
expression, not the start of an argument list.

For comparison,

puts(-3).abs

is parsed as

(puts(-3)).abs

and because puts returns nil, this is nil.abs (which fails)