Getting pipe return codes from SYSTEM command

I'm trying to find the return codes from bash for piped commands. i.e.

system("ls")

puts("#{$?.exitstatus}")

This returns the return code of ls

system("ls | bzip2 -c > ./out.txt")

how can I still get the return code of ls?

Thanks,

Russell.

···

--
Posted via http://www.ruby-forum.com/.

you cannot. this is a bash limitation.

if you need to do that use something like:

stdout = IO.popen('ls'){|pipe| pipe.read}

p $?.exitstatus

stdout = IO.popen('bzip2 -c', 'r+'){|pipe| pipe.write stdout; pipe.close_write; pipe.read}

p $?.exitstatus

a @ http://codeforpeople.com/

···

On May 7, 2008, at 9:33 AM, Russell Quinn wrote:

how can I still get the return code of ls?

--
we can deny everything, except that we have the possibility of being better. simply reflect on that.
h.h. the 14th dalai lama

system("ls | bzip2 -c > ./out.txt")

how can I still get the return code of ls?

If you're using bash then it has an shell variable that records the exit
status of all commands in a pipeline (it's an array). Do 'man bash'.

···

--
Posted via http://www.ruby-forum.com/\.

Thanks for the reply. But there is a pipestatus array in bash isn't
there?

ls | foo

echo ${PIPESTATUS[0]}

see:
http://aplawrence.com/Blog/B955.html

I just couldn't get it to work from Ruby

···

--
Posted via http://www.ruby-forum.com/.

Russell Quinn wrote:

ls | foo

echo ${PIPESTATUS[0]}

I just couldn't get it to work from Ruby

try 'ls | echo; exit ${PIPESTATUS[0]}'

···

--
Posted via http://www.ruby-forum.com/\.

that's because you've lost the bash process by the time bash exits. use my session gem if you want a persistent bash session against which to run commands:

require 'session'

bash = Session::Bash.new

stdout, stderr = bash.execute 'ls | grep something'
p bash.status

stdout, stderr = bash.execute 'echo ${PIPESTATUS[0]}'
p bash.status

etc. session uses a *single* bash session for all it's commands so you can do this sort of thing. however i'm not sure what the point is when pipelining from ruby, without shelling out, is so easy?

regards.

a @ http://codeforpeople.com/

···

On May 7, 2008, at 9:50 AM, Russell Quinn wrote:

Thanks for the reply. But there is a pipestatus array in bash isn't
there?

ls | foo

echo ${PIPESTATUS[0]}

see:
Bash shell $PIPESTATUS

I just couldn't get it to work from Ruby
--

--
we can deny everything, except that we have the possibility of being better. simply reflect on that.
h.h. the 14th dalai lama

try 'ls | echo; exit ${PIPESTATUS[0]}'

Magical! thanks :slight_smile:

···

--
Posted via http://www.ruby-forum.com/\.