简体   繁体   English

如果我将输出通过管道传输到 tee,则无法“继续”

[英]Can't "continue" if I pipe output to tee

I have a bash script that does pretty-much what I want using the following structure:我有一个 bash 脚本,它使用以下结构几乎可以完成我想要的操作:

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

I need to change it so the output goes both to the terminal and the log file.我需要更改它,以便输出同时发送到终端和日志文件。 This, however, doesn't work:但是,这不起作用:

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

It looks like, by creating a process, the pipe prevents me from using continue .看起来,通过创建一个进程,管道阻止我使用continue

Of course, I could rewrite the logic of my script without continue , but before I jump into that, I'm wondering if I'm missing a more straightforward way to achieve what I want.当然,我可以在不使用continue情况下重写我的脚本逻辑,但在我开始之前,我想知道我是否缺少一种更直接的方法来实现我想要的。

You could redirect the output to a process substitution.您可以将输出重定向到进程替换。

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

But why not just redirect the output of the whole loop?但是为什么不重定向整个循环的输出呢?

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

You could exit from the subprocess.您可以退出子进程。 If you would do that, I would suggest replacing { } with ( ) just to be safe if you one day decide to remove the tee .如果您愿意这样做,我建议您将{ }替换为( )以确保安全,如果您有一天决定移除tee

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM