Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: Bug with trap?

On Fri, Apr 30, 2010, Omari Norman wrote about "Bug with trap?":
> It seems that the trap builtin with the EXIT argument does not work
> properly if you have a list inside curly braces and the output is piped
> to another command. For example:
> { trap "echo exit trap running" EXIT} | cat
> Thus the trap in the last example simply did not run. You can try this
> with another command in the trap (e.g. touch, or rm) and you will get
> the same result: the trap does not run.
> This is zsh 4.3.6 on Debian 5.0. Is this a bug or am I missing
> something?

This is not a bug, but rather a result of the way that shells (not just zsh)
do pipes. When you have the pipe

	a | b

the command "a" runs in a subshell (a child process), while the command "b"
runs in the current shell, and they communicate through a pipe. Because "a"
runs in a separate process, one of the results is that it cannot influence
settings of the current shells - it cannot set environment variables, traps,
and so on.

For example if you do
	echo $a

Obviously, you get 3

But if you do
	{ a=3 } | cat
	echo $a

a is not set.

On the other hand if you do
	echo | {a=3;}
	echo $a

Again, a is set to 3. This goes to show you that it is the second part of
the pipe, not the first, which runs in the current shell, and only this part
of the pipe can influence things like traps or variables.


Nadav Har'El                        |       Monday, May  3 2010, 20 Iyyar 5770
nyh@xxxxxxxxxxxxxxxxxxx             |-----------------------------------------
Phone +972-523-790466, ICQ 13349191 |I had a lovely evening. Unfortunately,
http://nadav.harel.org.il           |this wasn't it. - Groucho Marx

Messages sorted by: Reverse Date, Date, Thread, Author