【问题标题】:Bash - redirect stdout to log and screen with stderr only to logBash - 将 stdout 重定向到日志并使用 stderr 进行屏幕仅用于日志
【发布时间】:2012-11-16 07:07:58
【问题描述】:

我想做以下事情;

  1. 将 stdout 的副本重定向到日志文件并将 stdout 保留在屏幕上。
  2. 将 stderr 重定向到同一个日志文件,并且不显示在屏幕上。

没有标准输出到屏幕的代码

#!/bin/bash
exec 1> >(sed -u 's/^/INF: /' >> common.log)
exec 2> >(sed -u 's/^/ERR: /' >> common.log)
echo "some txt"
echo "an error" >&2
echo "some more txt"
echo "one more error" >&2

日志

INF: some txt
INF: some more txt
ERR: an error
ERR: one more error

第一个问题是缓冲,我试图用 sed '-u' 否​​定它以表示无缓冲。

标准输出到屏幕的代码

#!/bin/bash
exec 1> >(sed -u 's/^/INF: /' | tee -a common.log)
exec 2> >(sed -u 's/^/ERR: /' >> common.log)
echo "some txt"
echo "an error" >&2
echo "some more txt"
echo "one more error" >&2

导致屏幕挂起(必须按 Ctrl-C)并且日志仍处于缓冲状态。有什么建议吗?

【问题讨论】:

    标签: bash redirect stdout stderr tee


    【解决方案1】:

    这对你有用吗?

    command 2> >(sed -u 's/^/ERR: /' >> common.log) | sed -u 's/^/INF: /' | tee -a common.log
    

    command 是您的命令。

    【讨论】:

    • 对于给定的命令是的,但我想要整个命名空间,因此使用 exec。我可以将特定部分包装在 {} 或函数本身上并使用您的解决方案,但这并不理想。
    • 鉴于没有更好的选择,我将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多