Skip to main content

New Rails Plugin to shell out with verbose error handling

Blog post   •   Apr 28, 2009 12:56 GMT

I was annoyed with the fact that when you use Ruby backticks (i.e. `some_shell_command`) to shell out to an external program and the path to the program is wrong then no exception is raised. In addition, using system and backticks doesn't allow you to capture standard error. I decided to write a little plugin called shell that allows you to do things like this:

status, output, error = Shell.run("/opt/local/bin/curl http://example.com")
# Raise exception on failure:
status, output, error = Shell.run!("/opt/local/bin/curl http://example.com")
It turns out some commands will indicate success with an exit code of 0 but still write to standard error. I have put in a special case in the Shell class that treats "No such file or directory" as a failure eventhough we have a zero exit code in that case.

I'm curious to hear from if there is a simpler and more idiomatic way to do this. It seems odd that I have to write a Rails plugin to invoke external programs in an elegant and convenient way.

Comments (2)

    I was wondering about that too, as I got fed up with all the STDOUT/STDERR capture glitches, looked around and found the systemu gem http://rubyforge.org/frs/?group_id=1024&release_id=16855 . It's advertised as being *nix/windows compatible, so probably worth a look too.

    - Evgeniy Dolzhenko - May 04, 2009 06:06 GMT

    Hi!

    Thanks for such a knowledgeable post.

    <a href="http://airul.id/tech/">Airultech</a>

    - Market Research Vietnam - May 13, 2016 08:40 GMT

Add comment

Comment