PDA

View Full Version : How to exit shell script if error occurs in pipeline



greenrd
21st June 2004, 02:31 AM
Suppose I have this line in a shell script


foo | tee bar

How do I make it so the script will exit if foo exits with a non-zero error code? (Preferably I want the script to return the same error code as foo returned.)

Normally, I would do:


foo || exit $?

but because of the
| I can't seem to get that to work.

ghenry
21st June 2004, 03:22 AM
Have you read the:

http://www.tldp.org/LDP/Bash-Beginners-Guide/html/index.html

and

http://www.tldp.org/LDP/abs/html/index.html


All the answers are in these.

greenrd
21st June 2004, 04:32 AM
Thanks for the links - thanks to those, and a usenet post, I figured out one way to do it:



# Put the pipeline to be executed before safepipe.
safepipe () {
T=$PIPESTATUS
for i in ${T[@]}; do
if [ $i -ne 0 ]; then
exit $i
fi
done
}

foo | tee bar
safepipe


However, I am wondering if there is a shorter / clearer way to do it.

Jman
21st June 2004, 04:39 AM
Moved to Programming forum.

ghenry
21st June 2004, 09:14 AM
I would send an e-mail to the fedora-list, loads more shell guys there.