Hi. I haven’t written Ruby in a while, and I was wondering if someone
could help with a problem I’ve never managed to solve. I’m writing a
shell script that takes filenames as its arguments, and calls “du” to
get their size. Because I don’t want to have to escape everything
perfectly, I was looking for a function with a syntax that allows
separate arguments, like system(“du”, “-sh”, filename).
system() doesn’t allow me to capture the output of the subprocess,
while popen , ``, and %x() don’t let me specify a list of discrete
arguments. Is there an elegant solution to this problem? My current
solution is to just escape the arguments and put them into a string,
but this is ugly and buggy.
Hi. I haven’t written Ruby in a while, and I was wondering if someone
could help with a problem I’ve never managed to solve. I’m writing a
shell script that takes filenames as its arguments, and calls “du” to
get their size. Because I don’t want to have to escape everything
perfectly, I was looking for a function with a syntax that allows
separate arguments, like system(“du”, “-sh”, filename).
def backtick(cmd,*args)
IO.popen(‘-’) {|f| f ? f.read : exec(cmd,*args)}
end
arguments. Is there an elegant solution to this problem? My current
solution is to just escape the arguments and put them into a string,
but this is ugly and buggy.
One possibility might be to let Shellwords handle the
escaping:
Thanks, Bill. I’m glad to hear that the standard library will be
getting the capability to do this without a hack, because it seems
like a big omission in ruby-1.8.
That comes a lot closer to working than I had expected
I’d rather not deal with escaping, at all. Won’t shell commands in
backticks be run differently, depending on what the system shell is?
I’m not sure whether all unix shells have similar escaping syntax.
The escaping done by inspect() seems to fail when the filename begins
with whitespace or contains a newline.
That comes a lot closer to working than I had expected
I’d rather not deal with escaping, at all. Won’t shell commands in
backticks be run differently, depending on what the system shell is?
I’m not sure whether all unix shells have similar escaping syntax.
The escaping done by inspect() seems to fail when the filename begins
with whitespace or contains a newline.
If you are on 1.9, escaping is superfluous: you can pass an Array of
arguments directly:
This is a lot safer, significantly less error prone and is probably
more efficient as well (because there is no shell needed for parsing
the command line).
Won’t shell commands in backticks be run differently, depending on what the system shell is? I’m not sure whether all unix shells have similar escaping syntax.
I don’t believe so. I think backticks will default to the lowest common
denominator of sh.
James Edward G. II
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.