1

除了将标准错误流合并到源脚本的标准输出流之外,这很好用。关于如何修复它的任何建议?

#!/usr/bin/env bash

# Source this from a script to capture and `tee` standard error and standard 
# out to a log file. Calling script must source this script.  For Example:
#
# . /usr/bin/logy /var/log/project/$0.log
#
# The logging uses >(process substitution). Process substitution is supported 
# in shells like bash and zsh but is not supported in sh.

_LOG=${1?log file}
test $# -eq 1 || exit 1

mkdir -p "$(dirname "$_LOG")"

# Append stdout and stderr to log file
exec > >(
  echo -e "START\t$(date)" >> "$_LOG"
  tee -a "$_LOG"
  echo -e "END\t$(date)" >> "$_LOG"
) 2>&1

这是一个例子:

. /usr/bin/logy $0.log
echo stdout
echo stderr >&2
exit 1

运行脚本:

$ ./t
$ echo $?      # $? is the return value
1

很好,返回值 1 被保留了……

记录了什么?

$ cat t.log
START    Thu, Feb 07, 2013  2:58:57 PM
stdout
stderr
END    Thu, Feb 07, 2013  2:58:57 PM

这个想法是制作单个日志文件,然后用于logrotate维护它们。

这是问题所在。标准输出和错误流被合并。此输出表明标准错误流已进入标准输出:

./t > /dev/null

这从 echo 语句中输出两行,显示两者都进入标准输出:

./t 2> /dev/null

有没有一种很好的方法来保留流,同时保留 stdout/err 语句的日志文件中的顺序?出于这个原因,我不认为两种exec陈述是一种选择。

4

1 回答 1

1

好先生,这应该工作

script_name.sh |& tee -a /var/log/script_name.sh.log

澄清部分命令

|& was added to Bash 4 as an abbreviation for 2>&1 |
于 2013-02-08T23:02:47.193 回答