如何在bash脚本中将std和err输出到单独的命令?

如何在bash脚本中将std和err输出到单独的命令?,bash,shell,Bash,Shell,我有一个bash脚本执行一个长时间运行的命令。我想在命令打印到stdout的每一行前面加上$stdprefix前缀,在打印到stderr的每一行前面加上$errprefix前缀 我不想将输出存储到变量或更糟的文件中,因为我必须等到命令执行完毕才能看到输出。您可以使用: # your prefixes stdprefix="stdout: " errprefix="stderr: " # sample command to produce output and error cmd() { ech

我有一个bash脚本执行一个长时间运行的命令。我想在命令打印到stdout的每一行前面加上$stdprefix前缀,在打印到stderr的每一行前面加上$errprefix前缀

我不想将输出存储到变量或更糟的文件中,因为我必须等到命令执行完毕才能看到输出。

您可以使用:

# your prefixes
stdprefix="stdout: "
errprefix="stderr: "

# sample command to produce output and error
cmd() { echo 'output'; echo >&2 'error'; }
现在独立重定向stdout和stderr:

{ cmd 2>&3 | awk -v p="$stdprefix" '{print p $0}'; } 3>&1 1>&2 |
  awk -v p="$errprefix" '{print p $0}'
stderr: error
stdout: output

只要用长时间运行的命令替换
cmd

谢谢。我还将第二个awk的输出重定向到stderr。它看起来是这样的:{cmd 2>&3|awk-vp=“$stdprefix”{print p$0}}}3>&1>&2|awk-vp=“$errprefix”{print p$0}>&2我在前面的评论中建议的重定向将所有内容打印到stderr。无论如何,在研究你的答案的过程中,我发现这很有魅力。因此,我的最后一个代码是
cmd 2>>(sed's/^/$errprefix/'>&2)| sed's/^/$stdprefix/'
是的,您也可以使用进程替换,但请确保在使用stdout之前重定向stderr。基本上是
cmd2>>(stderr|u handler)| stdout|u handler
表单。