首页 > 解决方案 > 返回 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

如何返回管道代码块中设置的值?

标签: sh

解决方案


问题不在于花括号,而在于管道。用进程替换替换它,问题就消失了。在 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"

推荐阅读