According to this accepted SOF answer:
In a pipeline, all commands run concurrently (with their stdout/stdin connected by pipes) so in different processes.
So although the curly braces by themselves do not create a subshell, the pipe then does this (in bash); see e.g.
#!/bin/bash
var=256
ps -u | grep $0
{
ps -u | grep $0
{
var="123"
export var
echo "var is "$var
ps -u | grep $0
} | tee log.txt
echo "var is "$var
}
echo "var is "$var
So what we want is avoiding the pipe, while still having output on screen and to the logfile.
Luckily bash got the feature <(...) for creating temporary FIFOs. Example below shows a possibility where one still can use a code block, transfer its whole output to a log (here stdout and stderr are appended to different log files) and have the changed variables accessible later, as we do not get into a subshell.
#!/bin/bash
VAR=123
echo "VAR first: $VAR"
{
VAR=256
echo "VAR in block: $VAR"
norealcommand
# show open files to see FIFOs
#lsof -p $$
date
otherbadcommand
}> >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
# dummy output to not mess up output order
echo | cat
#lsof -p $$
echo "VAR after block: $VAR"
cat -n stdout.log
cat -n stderr.log
which should result in something like this:
$ ./fifo /dev/shm |myself@mydesk|0|12:04:10
VAR first: 123
VAR in block: 256
./fifo: line 9: norealcommand: command not found
Mon Jul 3 12:04:37 CEST 2017
./fifo: line 13: otherbadcommand: command not found
VAR after block: 256
1 VAR in block: 256
2 Mon Jul 3 12:04:10 CEST 2017
3 VAR in block: 256
4 Mon Jul 3 12:04:37 CEST 2017
1 ./fifo: line 9: norealcommand: command not found
2 ./fifo: line 13: otherbadcommand: command not found
3 ./fifo: line 9: norealcommand: command not found
4 ./fifo: line 13: otherbadcommand: command not found
Hope this makes you happy :-)