Return values in pipelines
Maarten Litmaath
maart at cs.vu.nl
Fri Aug 24 03:34:22 AEST 1990
In article <1990Aug22.211057.19850 at agate.berkeley.edu>,
ilan343 at violet.berkeley.edu writes:
)
) The /bin/sh (and the ksh) set the parameter ? to the return value of
) the last excuted command. When I use a number of piped commands, say
)
)prog1 | prog2 | prog3 ,
)
)$? is set to the return value of the last command in the pipeline
)(prog3) . How can I detect if something went wrong on the previous
)commands in the pipeline (prog2, prog3)?
You can do something like this:
-------------------------------------------------------------------------------
#!/bin/sh
exec 3>&1 # Make file descriptor 3 a duplicate of stdout.
# Below: make fd 4 a dup of the new stdout, i.e. the output stream
# that's being captured.
# Then execute each but the last component of the pipeline in a subshell,
# with fd 3 closed (it doesn't need 3).
# In each subshell execute the command with fd 4 closed as well.
# Then echo the exit status to the remembered captured stdout.
# Before executing the last component of the pipeline, connect its stdout
# to the original stdout, and close fd 3.
error=`
exec 4>&1
(A 4>&-; echo A=$? >&4) 3>&- |
(B 4>&-; echo B=$? >&4) 3>&- |
(C 4>&-; echo C=$? >&4) 3>&- |
(D 4>&-; echo D=$? >&4) >&3 3>&-
`
exec 3>&-
case $error in
*=[1-9]*)
echo "Cut off mee legs an' call me shorty if it ain't wrong! Lessee:"
echo "$error"
;;
*)
echo "That's a big ten-four, little buddy!"
;;
esac
--
"[Your C code] seems about as portable as the Rock of Gibraltar."
(Wayne Throop)
More information about the Comp.unix.questions
mailing list