Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
#!/bin/bash

echo "Command before the redirected subshell"
OP=$(
    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
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. – user193607 Jan 29 '13 at 4:52

Your Answer

 
discard

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