我想要一个脚本,其中所有命令都tee
写入日志文件。
现在我正在运行脚本中的每个命令:
<command> | tee -a $LOGFILE
有没有办法强制 shell 脚本中的每个命令通过管道传输到tee
?
我不能强制用户tee
在运行脚本时添加适当的 ing ,并且即使调用用户没有添加自己的日志记录调用,也希望确保它正确记录。
您可以在脚本中进行包装:
#!/bin/bash
{
echo 'hello'
some_more_commands
echo 'goodbye'
} | tee -a /path/to/logfile
编辑:
这是另一种方式:
#!/bin/bash
exec > >(tee -a /path/to/logfile)
echo 'hello'
some_more_commands
echo 'goodbye'
为什么不公开一个简单的包装器:
/path/to/yourOriginalScript.sh | tee -a $LOGFILE
你的用户不应该执行(甚至不知道)yourOriginalScript.sh
。
假设您的脚本不带--tee
参数,您可以这样做(如果您确实使用该参数,只需将--tee
下面的参数替换为您不使用的参数):
#!/bin/bash
if [ -z "$1" ] || [ "$1" != --tee ]; then
$0 --tee "$@" | tee $LOGFILE
exit $?
else
shift
fi
# rest of script follows
这只是让脚本自己重新运行,使用特殊参数--tee
来防止无限递归,将其输出通过管道传输到tee
.
一些方法是创建所有用户调用他们自己的脚本的运行器脚本“run_it”。
run_it my_script
所有的魔法都将在内部完成,例如可能看起来像这样:
LOG_DIR=/var/log/
$@ | tee -a $LOG_DIR/