Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I would like to capture a subshell's output in a variable and print it in the terminal screen simultaneously. Is it possible to do this by assigning the subshell to a variable and piping stdout and stderr to tee? The following script is not working.

$ cat test

echo "Command before the redirected subshell"
    echo "Command in the redirected subshell 1"
    echo "Command in the redirected subshell 2"
    echo "Error in the redirected subshell" > /dev/stderr
    ) 2>&1 | tee /dev/tty
echo "Command after the redirected subshell"
echo "OP=$OP"

There is no output for the commands (except the one redirected to stderr) in the subshell and $OP seems to be a zero-length string.

Thanks for any idea!

share|improve this question

1 Answer 1

up vote 4 down vote accepted

Try this:

op=$( (cmd1; cmd2; ... ; cmdN) | tee /dev/tty )
share|improve this answer
Thanks! It is working now. So I need to create to nested shells then. –  sdr56p Jan 29 '13 at 4:52

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.