A bash irritation

April 7, 2006

Presented in illustrated form:

; cat foo
cat "$@"
; ./foo /etc/termcap | sed 1q >/dev/null
./foo: line 2: 3632 Broken pipe  cat "$@"

This behavior is new in Bash 2, as far as I know. I find it extremely irritating, because programs having broken pipes is perfectly normal in Unix. Many filters and so on don't consume all of their input, and no other implementation of the Bourne shell reports this (as far as I know).

(I would not mind so much if this was only reported for interactive sessions; it is that bash spews out this message in shell scripts that irritates me so much.)

As the BASH FAQ covers in its section E2, this can be disabled when people compile bash. Debian apparently usually compiles bash this way (good for them); Red Hat does not (sigh). Of course this solution only helps people who can recompile and reinstall bash on all of the systems they want their shell scripts to run nicely on.

You can muzzle much of the verbosity of this by adding a do-nothing trap for SIGPIPE. Unfortunately you can't get it all; the best you can do is:

; cat foo2
trap ':' 13; cat "$@"; exit 0
; ./foo2 /etc/termcap | sed 1q >/dev/null
Broken pipe

The message comes from bash itself. If you trap signal 13 to nothing at all, bash will set SIGPIPE to 'ignored' (SIG_IGN) for all of the processes in the pipe, which will cause them to see write errors instead of dying when the pipe breaks, which gets you:

; cat foo3
trap '' 13; cat "$@"; exit 0
; ./foo3 /etc/termcap | sed 1q >/dev/null
cat: write error: Broken pipe

Which error message you prefer is a matter of taste. I tend to go for the foo3 case, because at least then I can remember why I am getting these strange messages (and grind my teeth about it yet again).

Comments on this page:

I questioned this bash behavior again in 2015. You can following the link to the bash mailing list discussion through: http://www.pixelbeat.org/programming/sigpipe_handling.html

Written on 07 April 2006.
« A pleasing Python regularity with __future__
A common socket programming mistake: not handling short IO »

Page tools: View Source, View Normal, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Fri Apr 7 20:31:42 2006
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.