Return 在 POSIX sh 的管道内的块中设置的值

Return a value set in a block within a pipeline in POSIX sh

我想记录脚本的输出;因此,我从包含我的大部分代码的块中通过管道传输到 tee。但是,我遇到了管道退出时变量值丢失的问题。例如:

{
  (exit 3) # do something
  result=$?
} 2>&1 | tee -ia /var/log/action.log

exit "$result" # this needs to also exit with status 3

如何 return 在管道代码块中设置值?

问题不在于花括号,而在于管道。将其替换为流程替换,问题就消失了。在 bash 中(因为问题最初被标记为):

#!/usr/bin/env bash
#              ^^^^- NOT sh
{
  # do something
  result=$?
} > >(tee -ia /var/log/action.log) 2>&1

exit "$result"

而使用 POSIX sh,您可能会得到更像这样的结果:

#!/bin/sh
tempdir=$(mktemp -d "${TMPDIR:-/tmp}/myprogram.XXXXXX") || exit
mkfifo "$tempdir/fifo" || exit
tee -ia /var/log/action.log <"$tempdir/fifo" &

{
  rm -rf -- "$tempdir" # no longer needed after redirections are done
  # ...other code here...
  result=$?
} >"$tempdir/fifo" 2>&1

exit "$result"