[英]Start and stop logging terminal output to file from within bash script
基于以下三个问题:
...我整理了下面包含的脚本testlogredir.sh
。 它试图做的是:运行三个命令,它们的stdout和stderr输出将被记录到终端和日志文件中; 然后再运行两个命令,它们的stdout和stderr输出仅发送到终端。 实际上,它在保留终端输出的同时,开始和停止将脚本的终端输出重定向到日志文件。
有趣的是,如果我在停止日志到文件后使用sleep
,那么一切都会按预期进行:
$ bash testlogredir.sh 1 y
--- testlogredir.sh METHOD=1 DOSLEEP=y ---
aaa
bbb
ccc
ddd
eee
$ cat test.log
aaa
bbb
ccc
...并且通过运行bash testlogredir.sh 2 y
也可以获得相同的结果。
有趣的是,如果我不使用sleep( bash testlogredir.sh 1
也将获得相同的输出):
$ bash testlogredir.sh 2
--- testlogredir.sh METHOD=2 DOSLEEP= ---
ddd
eee
$ aaa
bbb
ccc
^C
$ cat test.log
aaa
bbb
ccc
...值得注意的是, 最后一个 “ ddd
”和“ eee
”首先输出到终端; 然后出现提示,然后输出第一个“ aaa
”,“ bbb
”,“ ccc
”-整个过程锁定。 所以我必须按Ctrl-C(^ C)退出它。 但是,日志文件确实具有预期的内容。
我推测,在没有睡眠的情况下,在bash解释器通过脚本跑这么快,它成功地呼应了“最后”二“ ddd
”和“ eee
第一 ” -然后才做tee
输出它已经存储了(注这不是由于tee
缓冲行为所致,因为我也尝试过使用stdbuf
获得相同的结果),而且显然是由tee
进行阻塞。 因此,添加sleep
可以使bash脚本与tee
(sub?)进程“同步”。
显然,我希望命令输出按顺序显示- sleep
本身并不会给我带来太大的麻烦,因为我可以将其设置为sleep 0.1
,几乎不会注意到它。 但是我不得不问-这是从bash
脚本中进行这种开始/停止“ tee
”重定向的正确方法吗? 换句话说-是否可以使用sleep
来实现这种“同步”呢?
testlogredir.sh
#!/usr/bin/env bash
# testlogredir.sh
# defaults:
METHOD="1" # or "2"
DOSLEEP="" # or "y"
if [ "$1" ] ; then
METHOD="$1" ;
fi
if [ "$2" ] ; then
DOSLEEP="$2" ;
fi
# this should be echoed only to terminal
echo " --- $0 METHOD=$METHOD DOSLEEP=$DOSLEEP ---"
# silent remove of test.log
rm -f test.log
if [ $METHOD == "1" ] ; then
# Redirect 3 into (use fd3 as reference to) /dev/stdout
exec 3> /dev/stdout
# Redirect 4 into (use fd4 as reference to) /dev/stderr
exec 4> /dev/stderr
fi
if [ $METHOD == "2" ] ; then
# backup the original filedescriptors, first
# stdout (1) into fd6; stderr (2) into fd7
exec 6<&1
exec 7<&2
fi
# Redirect stdout ( > ) into a named pipe ( >() ) running "tee"
#~ exec > >(stdbuf -i0 -o0 tee test.log)
exec > >(tee test.log)
# Redirect stderr (2) into stdout (1)
exec 2>&1
# these should be echoed both to terminal and log
echo "aaa"
echo "bbb"
echo "ccc" >&2
if [ $METHOD == "1" ] ; then
# close current stdout, stderr
exec 1>&-
exec 2>&-
# Redirect stdout (1) and stderr (2)
exec 1>&3
exec 2>&1
fi
if [ $METHOD == "2" ] ; then
# close and restore backup; both stdout and stderr
exec 1<&6 6<&-
exec 2<&7 2<&-
# Redirect stderr (2) into stdout (1)
exec 2>&1
fi
if [ "$DOSLEEP" ] ; then
sleep 1 ;
fi
# these should be echoed only to terminal
echo "ddd"
echo "eee" >&2
exit
您可以使用花括号来重定向命令以通过管道进行tee
#!/bin/bash
# to terminal and logfile.log
{
echo "aaa"
echo "bbb"
echo "ccc"
} 2>&1 | tee logfile.log
# only terminal
echo "ddd"
echo "eee"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.