强制`tee`为shell脚本中的每个命令运行?

war*_*ren 4 linux bash shell logging tee

我想有一个脚本,其中所有命令都是tee日志文件.

现在我正在运行脚本中的每个命令:

<command> | tee -a $LOGFILE
Run Code Online (Sandbox Code Playgroud)

有没有办法强制shell脚本中的每个命令管道tee

我无法强制用户tee在运行脚本时添加适当的ing ,并且即使主叫用户没有添加他们自己的日志记录调用,也希望确保它正确记录.

Pau*_*ce. 15

您可以在脚本中执行包装:

#!/bin/bash
{
echo 'hello'
some_more_commands
echo 'goodbye'
} | tee -a /path/to/logfile
Run Code Online (Sandbox Code Playgroud)

编辑:

这是另一种方式:

#!/bin/bash
exec > >(tee -a /path/to/logfile)
echo 'hello'
some_more_commands
echo 'goodbye'
Run Code Online (Sandbox Code Playgroud)

  • 如果您正在记录一个文件中发生的所有事情,请使用 `exec &gt;&gt;(tee -a /path/to/logfile) 2&gt;&amp;1` 将错误也输出到文件中。“-a”是附加的,但您也可以删除它以便每次都从文件开始。 (3认同)