Bash脚本将stdout和stderr写入终端并分离日志文件

时间:2020-10-12 10:05:10

标签: bash shell

我想创建一个执行以下操作的bash脚本:

  • 将stdout和stderr写入终端
  • 将stdout和stderr写入info.log并以日期和时间作为前缀
  • 将stderr写入error.log,并在其前面加上日期和时间
  • 调用多个其他bash脚本,如果其中一个不以0退出,则退出
  • 使用相同的退出代码退出第一个失败的脚本

在我当前的脚本中,终端中的输出未按时间顺序排列……似乎使用tee的重定向执行了异步操作。

这是我当前的脚本:

#!/bin/bash

info_log_path="info.log"
error_log_path="error.log"

bashtrap()
{
   echo "Job finished with Exitcode $?"; exit $?;
}

trap bashtrap EXIT ERR

#exit on first errror:
#set -e

# redirect stdout and stderr to info log
exec &> >( tee >(while IFS= read -r line; do printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"; done >>"$info_log_path"))
# redirect stderr to error log
exec 2> >( tee >(while IFS= read -r line; do printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$line"; done >>"$error_log_path"))

echo "Executing script1"
./script1

echo "Executing script2"
./script2

echo "Executing script3"
./script3

echo "Executing script4"
./script4

0 个答案:

没有答案