没有办法避免子shell 不能使父进程直接终止这一事实:父进程必须评估从子shell 返回的值。一种常见的技术是陷阱退出并在陷阱函数中打印错误消息。由于您在子 shell 中生成错误消息,因此您不能像其他方式那样简单地将消息分配给变量,但您可以使用文件系统。请注意,这个想法真的很傻,简单地将错误消息写入stderr要干净得多。这就是它的用途,这就是它被孩子继承的原因。就像是:
#!/bin/sh
trap final 0 2 15
# Create a temporary file to store error messages. This is a terrible
# idea: it would be much better to simply write error messages to stderr,
# but this code is attempting to demonstrate the technique of having the
# parent print the message. Perhaps it would do better to serve as an example
# of why reporting your children's mistakes is a bad idea. The children
# should be responsible for reporting their own errors. Doing so is easy,
# since they inherit file descriptor 2 from their parent.
errmsg=$( mktemp xxxxx )
final() {
test "$?" = 0 || cat $errmsg
rm -f $errmsg
} >&2
# Must emphasize one more time that this is a silly idea. The error
# function ought to be writing to stderr: eg echo "error: $*" >&2
error() { echo "error: $*" > $errmsg; exit 1; }
do_sth() {
if test "$1" -eq 0; then
error "First param must be greater than 0!"
else
echo "OK!"
fi
}
result=$( do_sth 0 ) || exit 1
echo not printed