Warm tip: This article is reproduced from serverfault.com, please click

shell-干净的方法来复制标准输入

(shell - Clean way to duplicate stdin)

发布于 2020-11-28 15:46:47

我想将stdin传递给两个不同的进程。有什么不错的干净方法可以做到这一点?

(我在下面提出了一种基于临时文件的方法,但是也许有更好的方法?)

GitHub的“ git lfs pre-push”预推钩子显示为stdin。我想安装第二个预推检查,例如在pre-push.sample中找到的WIP检查。这意味着我需要以某种合理的方式保存stdin,以便“ git lfs pre-push”和“ while read local_ref local_sha remote_ref remote_sha”循环都可以读取提交。

Questioner
Hugo
Viewed
11
glenn jackman 2020-11-29 00:28:25

你可以将其tee与输出过程替换一起使用

为了清楚起见,这里将单独的检查代码放入函数中:

check1() {
  git lfs pre-push "$@"
}

check2() {
  while read -ra variables; do
    : ...
  done
}

# redirecting to /dev/null so you don't get the original input as well
tee >(check1) >(check2) >/dev/null

我不确定这些限制,但是你可以通过这种方式进行任意数量的检查:

tee >(check1) \
    >(check2) \
    >(check3) ...

演示:

check1() { while IFS= read -r n; do echo $((n*5)); done; }
check2() { while IFS= read -r line; do echo ">>>$line<<<"; done; }
seq 101 100 1101 | tee >(check1) >(check2) >/dev/null

输出

505
>>>101<<<
1005
1505
2005
2505
3005
3505
>>>201<<<
4005
4505
>>>301<<<
5005
>>>401<<<
5505
>>>501<<<
>>>601<<<
>>>701<<<
>>>801<<<
>>>901<<<
>>>1001<<<
>>>1101<<<

由于两个检查都在子外壳程序中运行,因此输出顺序不确定。