2

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!

4

Try this:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy