将stdout和stderr重定向到带有前缀的单个文件

Joã*_*ela 8 bash redirect stdout stderr

我正在编写一个bash脚本,需要将运行的命令的输出stdout和stderr输出重定向到单个文件,并在每个行前面加上stderr或者stdout相应的前缀.

有一个简单的方法来做到这一点?

eph*_*ent 11

来自Debian的devscripts的annotate-output就是这样做的.

其手册页中的示例:

$ annotate-output make
21:41:21 I: Started make
21:41:21 O: gcc -Wall program.c
21:43:18 E: program.c: Couldn't compile, and took me ages to find out
21:43:19 E: collect2: ld returned 1 exit status
21:43:19 E: make: *** [all] Error 1
21:43:19 I: Finished with exitcode 2


mou*_*iel 10

试试这个:

(myCommand | sed s/^/stdout:/ >> myLogfile) 2>&1 | sed s/^/stderr:/ >> myLogFile
Run Code Online (Sandbox Code Playgroud)

第一个管道stdout:在标准输出中插入前缀myCommand并将其附加到myLogFile.

括号用于对所有这些进行单个命令.他们告诉我们进一步的重定向适用于括号内的内容,而不仅仅适用于sed.

然后将标准错误重定向到标准输出2>&1(请记住原始标准输出已经重定向到a myLogFile).第二个管道stderr:为其插入前缀并将其追加myLogFile.

  • 不幸的是,这种方法不保留秩序...... :( (3认同)