Vlad Skvortsov's Blog

cyrillic ditrack gtd guitar mac music pdf phd postscript productivity programming projects python r russian shell terminal tex tips utf-8 wadcomblog

My name is Vlad Skvortsov, I'm a software engineer: it's my job, hobby and addiction.

My primary interests include high-performance, scalable, fault-tolerant distributed systems; server-side applications; information retrieval technologies; procedural aspects of software engineering process.

I work on several private and open-source projects, hacking in Python, Haskell, Erlang, Perl and C.

Guitar, hiking, ice hockey and other hobbies help me to balance my life.

My e-mail is vss@73rus.com.

Bourne Shell Functions In Pipelines

Sep 23 2008, 11:02 permalink
Tags: shell tips

I 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))

f | cat

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)):
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.