bash 强制`tee` 为shell 脚本中的每个命令运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4037170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Force `tee` to run for every command in a shell script?
提问by warren
I would like to have a script wherein all commands are tee'd to a log file.
我想要一个脚本,其中所有命令都tee指向日志文件。
Right now I am running every command in the script thusly:
现在我正在运行脚本中的每个命令:
<command> | tee -a $LOGFILE
Is there a way to force every command in a shell script to pipe to tee?
有没有办法强制 shell 脚本中的每个命令通过管道传输到tee?
I cannot force users to add appropriate teeing when running the script, and want to ensure it logs properly even if the calling user doesn't add a logging call of their own.
我不能强迫用户tee在运行脚本时添加适当的ing ,并且即使调用用户没有添加他们自己的日志记录调用,也希望确保它正确记录。
回答by Paused until further notice.
You can do a wrapper inside your script:
你可以在你的脚本中做一个包装:
#!/bin/bash
{
echo 'hello'
some_more_commands
echo 'goodbye'
} | tee -a /path/to/logfile
Edit:
编辑:
Here's another way:
这是另一种方式:
#!/bin/bash
exec > >(tee -a /path/to/logfile)
echo 'hello'
some_more_commands
echo 'goodbye'
回答by Vinko Vrsalovic
Why not expose a wrapper that's simply:
为什么不公开一个简单的包装器:
/path/to/yourOriginalScript.sh | tee -a $LOGFILE
Your users should not execute (nor even know about) yourOriginalScript.sh.
您的用户不应执行(甚至不知道)yourOriginalScript.sh。
回答by Adam Rosenfield
Assuming that your script doesn't take a --teeargument, you can do this (if you do use that argument, just replace --teebelow with an argument you don't use):
假设您的脚本不接受--tee参数,您可以这样做(如果您确实使用了该参数,只需将--tee下面的参数替换为您不使用的参数):
#!/bin/bash
if [ -z "" ] || [ "" != --tee ]; then
run_it my_script
--tee "$@" | tee $LOGFILE
exit $?
else
shift
fi
# rest of script follows
This just has the script re-run itself, using the special argument --teeto prevent infinite recursion, piping its output into tee.
这只是让脚本重新运行自己,使用特殊参数--tee来防止无限递归,将其输出管道到tee.
回答by Gadolin
Some approach would be creation of runner script "run_it" that all users invoke their own scripts.
一些方法是创建所有用户调用他们自己的脚本的运行脚本“run_it”。
LOG_DIR=/var/log/
$@ | tee -a $LOG_DIR/
All the magic would be done within, e.g. could look like that:
所有的魔法都将在其中完成,例如可能看起来像这样:
##代码##
