Sunday, September 28, 2008

Finding return values from chained pipe commands in the system function

I have already discussed some hints for the usage of the Ruby system method, but encountered another facet of using this system function while passing a bash command using pipes. The problem is that one gets the standard exitcode status back from bash via the $? variable. But when you use pipe to chain more than one command you only get the last command results back from the $? variable.

Enter the PIPEARRAY from bash, which allows you access to the each commands return value in the entire chain. The problem with Ruby is that this is not available after the system function ends. Again, using some  smart Bash you can exit your command chain with the contents of the PIPEARRAY like this:

# a system call that exits with the value of the first command 'make'.
system("make | tee output.log; exit ${PIPESTATUS[0]}")

# examine the returned value of the command 'make'
puts $?.exitstatus