I need the capture the output of a command group in BASH to STDOUT and a log file. Consider this code with command grouping and it's output
#!/usr/bin/bash
main(){
declare -i mycode=1
echo "Declared mycode:${mycode}"
{
#command group
echo "mycode:${mycode}"
mycode=2
echo "mycode:${mycode}"
} 2>&1
echo "mycode:${mycode}"
}
main
the output is:
Declared mycode:1
mycode:1
mycode:2
mycode:2
I need to capture the command group output to a log file and STDOUT so I add tee as follows:
#!/usr/bin/bash
main(){
declare -i mycode=1
echo "Declared mycode:${mycode}"
{
#command group
echo "mycode:${mycode}"
mycode=2
echo "mycode:${mycode}"
} 2>&1 | tee ~/log.log
echo "mycode:${mycode}"
}
main
but now the output is as follows:
Declared mycode:1
mycode:1
mycode:2
mycode:1
So value of the mycode variable does not get set to 2 in the outer scope when tee is used as the left of tee will be run in a subshell. For various reason I need mycode defined in the global scope so I need to avoid subshells.
How can I achieve the behaviour of tee without a subshell whereby I can stream output to STDOUT and a log file.