首页 文章

Bash - 将stdout重定向到日志和屏幕,只有stderr才能记录

提问于
浏览
2

我想做以下事情;

  • 将stdout的副本重定向到logfile并在屏幕上保留stdout .

  • 将stderr重定向到相同的日志文件,而不是在屏幕上显示 .

没有stdout到屏幕的代码:

#!/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'取消无缓冲 .

带stdout到屏幕的代码:

#!/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)和日志仍然缓冲 . 建议?

1 回答

  • 2

    这对你有用吗?

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

    command 是你的命令 .

相关问题