Assume the following script:#!/bin/shfunc1() {  eval $1'=$(cat)'  eval echo Value$2 inside function : \$$1}func1 x 1 <<'HEREDOC'Hello WorldHEREDOCecho Value1 outside function: $xx=echo Hello World | func1 x 2echo Value2 outside function: $xOn bash 4.3.43-4.fc25, the output is:Value1 inside function : Hello WorldValue1 outside function: Hello WorldValue2 inside function : Hello WorldValue2 outside function: Using the bashism shopt -s lastpipe makes the last line also show Hello World, but intuitively I don't understand why that doesn't happen automatically. Is this expected?It appears the POSIX standard doesn't really discuss this topic: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_09_02
Why doesn't the last function executed in a POSIX shell script pipeline retain variable values?
shell script;posix
POSIX says that:each command of a multi-command pipeline is in a subshell environmentand thatChanges made to the subshell environment shall not affect the shell environmentIf you think about the most straightforward way of implementing a pipeline, this makes sense - call pipe(), fork a subshell, and swap out standard output/input on one side each, then execute the command in the subshell. This is also the defined behaviour of Bash.You can't rely on that happening, though, becauseas an extension, however, any or all commands in a pipeline may be executed in the current environmentThat's what lastpipe does for that case. In some other shells, that's the default behaviour in certain situations.