Bourne Shell Functions In Pipelines
Sep 23 2008, 11:02 permalinkI spent quite some time trying to debug a simple shell script which used a function modifying global variables. The problem turned out to be a different behaviour of a shell function when that's called from a pipeline.
Here is a simple test case for that:
#! /bin/sh -e f () { echo "X=$X" X=$(($X + 1)) } X=1 f | cat f
The output of the script is not what I expected, but:
...because f | cat is a pipeline and thus although the function f is executed within the current shell, it doesn't affect the environment. This is documented, of course (sh(1)):X=1 X=1
Note that unlike some other shells, sh executes each process in the pipeline as a child of the sh process. Shell built-in commands are the exception to this rule. They are executed in the current shell, although they do not affect its environment when used in pipelines....and makes some sense. But still it was hard to find.