Bash 如何限制可能过于冗长的命令的输出?
我正在寻找一个bash代码段,用于限制shell命令可能变得过于冗长的控制台输出量 其目的是在生成/CI环境中使用,您确实希望限制控制台输出的数量,以防止CI服务器过载,甚至客户端跟踪输出 全部要求: 从命令输出的顶部开始最多只显示100行 从命令输出的底部尾部最多显示100行 将stdout和stderr全部归档到command.log.gz文件中 控制台输出必须相对实时地显示,在最后输出结果的解决方案是不可接受的,因为我们需要能够看到其执行进度。 目前的调查结果 unbuffer可用于强制取消缓冲stdout/stderr |&T形三通可用于将输出发送给架桥机和尾部/头部 |&gzip-stdout>command.log.gz可以归档控制台输出 head-n100和tail-n100可用于限制控制台输出。如果输出线的数量低于200,它们至少会带来一些问题,如不希望的结果。 这是我目前不完整的解决方案,为了方便起见,它演示了处理10行输出,希望将输出限制在前2行和最后两行Bash 如何限制可能过于冗长的命令的输出?,bash,stdout,Bash,Stdout,我正在寻找一个bash代码段,用于限制shell命令可能变得过于冗长的控制台输出量 其目的是在生成/CI环境中使用,您确实希望限制控制台输出的数量,以防止CI服务器过载,甚至客户端跟踪输出 全部要求: 从命令输出的顶部开始最多只显示100行 从命令输出的底部尾部最多显示100行 将stdout和stderr全部归档到command.log.gz文件中 控制台输出必须相对实时地显示,在最后输出结果的解决方案是不可接受的,因为我们需要能够看到其执行进度。 目前的调查结果 unbuffer可用于强制取
#!/bin/bash
seq 10 | tee >(gzip --stdout >output.log.gz) | tail -n2
据我所知,您需要在生成时在线限制输出。 这是一个我能想到的对你有用的函数
limit_output() {
FullLogFile="./output.log" # Log file to keep the input content
typeset -i MAX=15 # number or lines from head, from tail
typeset -i LINES=0 # number of lines displayed
# tee will save the copy of the input into a log file
tee "$FullLogFile" | {
# The pipe will cause this part to be executed in a subshell
# The command keeps LINES from losing it's value before if
while read -r Line; do
if [[ $LINES -lt $MAX ]]; then
LINES=LINES+1
echo "$Line" # Display first few lines on screen
elif [[ $LINES -lt $(($MAX*2)) ]]; then
LINES=LINES+1 # Count the lines for a little longer
echo -n "." # Reduce line output to single dot
else
echo -n "." # Reduce line output to single dot
fi
done
echo "" # Finish with the dots
# Tail last few lines, not found in head and not more then max
if [[ $LINES -gt $MAX ]]; then
tail -n $(($LINES-$MAX)) "$FullLogFile"
fi
}
}
在脚本中使用它,将其加载到当前shell或将其放入要在用户会话中加载的.bash_配置文件中
用法示例:cat/var/log/messages | limit_输出或./configure | limit_输出
该函数将读取标准输入,将其保存到日志文件中,显示第一个最大行,然后将每行减少为一个点。在屏幕上,如果输出短于MAX*2,则最终显示最后的MAX行或更少的行。实现这一点的一种方法是: /配置| tee output.log | head-n 5;tail-n2 output.log 它的作用是: 使用tee将完整输出写入名为output.log的文件 仅使用head-n打印前5行 最后,使用tail-n打印writed output.log中的最后两行 [-f command.log.gz]&&gunzip command.log.gz;somecommand>tmp&&$wc-L100&&{head-N100TMP;tail-N100TMP;}| | cat tmp;cat tmp>>command.log;gzip命令.log;rm TMP的可复制副本