Re: Ignoring trap command for a grep function
From: Henry Townsend (henry.townsend_at_not.here)
Date: Wed, 13 Jul 2005 19:06:14 -0400
Chris F.A. Johnson wrote:
> On 2005-07-13, firstname.lastname@example.org wrote:
>>We have a trap statement for every non zero returning command/function.
I don't make a habit of disagreeing with CFAJ but must make an exception
in this case. Using a trap on ERR in shell programming turns it into an
exception-throwing language like Java[*]; you can catch the exceptions
(non-zero exit statuses) that you care about as special cases and all
others result in fatal errors. It's as robust a shell programming style
as I know. If using ksh or bash you can add useful data such as
trap 'echo Failed at $0:$LINENO >&2' ERR
>>Are their any possibilities ? We want to avoid changing the design
>>involving the use of trap in and around the trap statement.
> The design is inappropriate for your script; change it.
I always tell people to add a new shell builtin to their lexicon: "||:"
(without the quotes). Of course it's really two old builtins jammed
together to mean "ignore preceeding exit status". In other words
'>/dev/null' means "throw away stdout", '2>/dev/null' means "throw away
stderr", and '||:' means "throw away return code". So you take your grep
command, and any others for which you don't want to fail on failure, and
stick ||: on the end:
grep foobar /etc/motd ||:
[*] The merits of exceptions vs manual error checking can be and have
been debated in other places; I simply note that the exception style
cannot be said to be "wrong", though some may not be used to or prefer
it. I happen to think you can't write a large reliable shell script
-- Henry Townsend