sh - 返回 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
如何返回管道代码块中设置的值?
解决方案
问题不在于花括号,而在于管道。用进程替换替换它,问题就消失了。在 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"
推荐阅读
- javascript - 将具有 onclick 功能的动态按钮添加到单元格
- java - UUID 的紧凑替代品作为相关 ID
- ios - 如何使用 Swift 5 将 Dropbox API 连接到 iOS 应用程序
- amazon-web-services - 新创建的 AWS 成员账户缺少 IAM 角色
- arrays - 如何在通过switch case选择的数组中添加元素
- vue.js - 如何使用 vuejs 为 div 添加颜色
- python - 多重继承和super()
- vue.js - $vuetify.goTo 在 v-dialog 全屏模式下不起作用
- rasa - 翻译 NLU 模型中 RASA 实体提取的问题
- gulp - 已解决 - gulp : 为网站构建几个 dist,每个都有自己的自定义 js