如果将管道输出到tee则无法继续

问题描述 投票:1回答:1

我有一个bash脚本,它使用以下结构几乎可以完成我想要的工作:

for x in 1 2 3
do
  {
  [[ $x -ne 2 ]] || continue
  echo $x
  } &>> foo.log
done

我需要更改它,以便输出同时到达终端和日志文件。但是,这不起作用:

for x in 1 2 3
do
  {
  [[ $x -ne 2 ]] || continue
  echo $x
  } 2>&1 | tee -a foo.log
done

看起来,通过创建进程,管道阻止了我使用continue

当然,我可以不用continue来重写脚本的逻辑,但是在我跳进去之前,我想知道我是否缺少一种实现我想要的更简单的方法。

bash io-redirection continue curly-braces
1个回答
0
投票

您可以将输出重定向到流程替换。

for x in 1 2 3
do
  {
  [[ $x -ne 2 ]] || continue
  echo $x
  } 2>&1 > >(tee -a foo.log)
done |
# I suggest to do pipe the output to ex. `cat`, so that the output 
# of process substitution will be synchronized with rest of the script
cat

但是为什么不仅仅重定向整个循环的输出呢?

for x in 1 2 3; do
  [[ $x -ne 2 ]] || continue
  echo $x
done 2>&1 | tee -a foo.log
© www.soinside.com 2019 - 2024. All rights reserved.