Monday, January 28, 2008

Ruby system function help and hints

Lately while using Ruby and trying to make sense of the system() function, which has a boolean return value, I was getting a bit frustrated. It seams you have one of two choices, so thought I would outline them here.

First, you can use the system(command) function which will execute your command in a subprocess and report a boolean success value. It should be noted that stdout will be available on the screen/console while the given command is running and you can redirect with the standard Linux commands (such as tee, |, >, >>, etc.).

The second option is to use what are called backticks, which allows you to capture the commands output into a variable. Note that you will no longer see stdout on the screen/console, but you will receive stderr on the screen/console. Usage is like this:

stdout = `#{command}`

It matters not whether you use the first or the second option, they both provide a means to check their resulting exit codes. I use the standard Bash variable $? like this:

exitcode = $?.exitstatus

These hints and tips should clarify the various options you have when accessing the underlying (Linux) system and to help you when trying to sort out what to do with the results of your commands.