Bash help requested: Capturing command errors within pipes

Cameron Simpson cs at zip.com.au
Thu Mar 19 23:17:47 UTC 2009


On 19Mar2009 12:19, Daniel B. Thurman <dant at cdkkt.com> wrote:
> OK, I found out why I had a problem!
>
> I setup an intentional sed error:
> $ (re="-e '\'s/b/h/'"; echo "boo" | sed $re | echo "done"; echo  
> ${PIPESTATUS})
> done
> sed: -e expression #1, char 1: unknown command: `''
> 0

[ I'm sure you know everything I say below based on previous posts, but
  it seems worth saying purely for other readers...
]

Ok, but I strongly recommend you never us a regexp unquoted - the
necessary backslash nesting gets nasty real fast. A better way is like
this:

  re='s/b/h/'
  sed -e "$re"

or for complex stuff, write a file called "sedf" (for example)
containing a full sed script:

  s/b/h/
  /foo/d
  /bah/b again

etc. Then:

  sed -f sedf

The point here, unrelated to the pipe exit status issue, is to keep the
sed stuff easy to write and undamaged by shell substitution.

On the pipe stuff, another approach (less convenient than PIPESTATUS),
is a flag approach like you original attempt, but using files:

  badness=/tmp/foo$$bad
  { x || touch $badness; } \
  | { y || touch $badness; } \
  | { z || touch $badness; }
  if [ -f $badness ]
  then
    rm $badness
    echo badness happened >&2
  fi

It has the advantage of working in non-pipe circumstances (nested
subshells, etc).

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

You don't stop riding because you get old, you get old because you stop
riding.         - Anon. on rec.motorcycles




More information about the fedora-list mailing list