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

Bash脚本将stdout和stderr写入终端并分离日志文件,bash,shell,Bash,Shell,我想创建一个bash脚本,它执行以下操作: 将stdout和stderr写入终端 将stdout和stderr写入info.log,并在其前面加上日期和时间 将stderr写入error.log并在其前面加上日期和时间 调用多个其他bash脚本,如果其中一个脚本没有使用0退出,则退出 从第一个失败脚本中使用相同的退出代码退出 在我当前的脚本中,终端中的输出不是按时间顺序排列的。。。似乎使用tee的重定向执行了异步操作 以下是我当前的脚本: #!/bin/bash info_log_path

我想创建一个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

您将陷阱设置为
EXTI
,而不是
ERR
。后者将为您提供
set-e
行为。尽管您为什么不简单地使用
set-e
?thx陷阱错误解决了第一个问题:)但实际上无法确保stderr和stdout按特定顺序打印。通过禁用缓冲,您可能会得到一些接近您希望的东西。我该怎么做?如果没有重定向,输出是有序的。。。重定向可能是顺序的,请注意,
在读取时;打印$(日期)
将非常慢。考虑使用<代码> AWK < /代码>将时间戳添加到线幅度更快。