使用 exec 和 tee 同时将日志重定向到 stdout 和日志文件

4m1*_*4j1 42 bash logs tee exec

在 bash 脚本中,如何使用 将所有标准输出重定向到日志文件和tee屏幕上的输出exec

log_file="$HOME/logs/install.txt-`date +'%Y-%m-%d_%H-%M-%S'`"
[ -f "$log_file" ] || touch "$log_file"
exec 1>> $log_file 2>&1
Run Code Online (Sandbox Code Playgroud)

此代码将所有日志重定向到日志文件而不是屏幕。

Mic*_*mer 82

使用带有重定向的进程替换和:&exec

exec &> >(tee -a "$log_file")
echo "This will be logged to the file and to the screen"
Run Code Online (Sandbox Code Playgroud)

$log_file 将包含脚本和任何子进程的输出,并且输出也将打印到屏幕上。

  • >(...)启动进程...并返回一个代表其标准输入的文件。

  • exec &> ...将标准输出和标准错误重定向到...脚本的其余部分(仅exec > ...用于 stdout)。

  • tee -a 将其标准输入附加到文件中,并将其打印到屏幕上。


小智 9

exec >> $log_file 2>&1 && tail $log_file
Run Code Online (Sandbox Code Playgroud)