重定向标准输出复制到从bash脚本本身的日志文件 [英] redirect COPY of stdout to log file from within bash script itself

查看:378
本文介绍了重定向标准输出复制到从bash脚本本身的日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何标准输出重定向到一个文件:

  EXEC> foo.log
echo测试

这将会把'测试'到foo.log文件。

现在我想将输出重定向到日志文件,并保持它在stdout

即。它可以从平凡要做的脚本之外:

 脚本|三通foo.log

但我想从里面做

我试过

  EXEC |三通foo.log

但它没有工作。


解决方案

 #!的/ usr / bin中/ env的庆典#重定向标准输出(大于)为命名管道(大于())上运行的三通
EXEC> >(TEE -i LOGFILE.TXT)#如果没有这个,只有标准输出将被捕获 - 即你
#日志文件中不含有任何错误消息。
#看到(和给予好评),答案由亚当·斯皮尔,这使STDERR
#作为一个单独的数据流 - 我不想简单地从他身上偷
#加入他的回答我的。
EXEC 2 - ;&放大器; 1回声富
回声酒吧>和2

请注意,这是庆典,而不是 SH 。如果调用与 SH myscript.sh 脚本,你会相处语法错误附近意外的标记线错误'>

如果您正在使用的信号陷阱时,您可能需要使用 T恤-i 选项,以避免在输出中断如果发生信号。 (感谢JamesThomasMoon1979的评论。)


工具的改变取决于他们是否写入到一个管道或终端的输出( LS 用色彩和栏目化输出,例如)将检测上述结构的意义它们输出到管道

有选项来执行彩色化/ columnizing(例如 LS -C --color =总是)。请注意,这将导致颜色codeS被写入日志文件,以及,使得它的的可读性。

I know how to redirect stdout to a file:

exec > foo.log
echo test

this will put the 'test' into the foo.log file.

Now I want to redirect the output into the log file AND keep it on stdout

i.e. it can be done trivially from outside the script:

script | tee foo.log

but I want to do it from the inside

I tried

exec | tee foo.log

but it didn't work

解决方案

#!/usr/bin/env bash

# Redirect stdout ( > ) into a named pipe ( >() ) running "tee"
exec > >(tee -i logfile.txt)

# Without this, only stdout would be captured - i.e. your
# log file would not contain any error messages.
# SEE (and upvote) the answer by Adam Spiers, which keeps STDERR
# as a seperate stream - I did not want to steal from him by simply
# adding his answer to mine.
exec 2>&1

echo "foo"
echo "bar" >&2

Note that this is bash, not sh. If you invoke the script with sh myscript.sh, you will get an error along the lines of syntax error near unexpected token '>'.

If you are working with signal traps, you might want to use the tee -i option to avoid disruption of the output if a signal occurs. (Thanks to JamesThomasMoon1979 for the comment.)


Tools that change their output depending on whether they write to a pipe or a terminal (ls using colors and columnized output, for example) will detect the above construct as meaning that they output to a pipe.

There are options to enforce the colorizing / columnizing (e.g. ls -C --color=always). Note that this will result in the color codes being written to the logfile as well, making it less readable.

这篇关于重定向标准输出复制到从bash脚本本身的日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆