2017-04-24 23 views
0

我正在寻找一个bash代码片段来限制可能会变得太冗长的shell命令的控制台输出量。如何限制可能过于冗长的命令的输出?

这样做的目的是为了防止过载CI服务器(甚至客户端拖尾输出)而在控制台输出上限制数量的build/CI环境中使用。

全部要求:

  • 显示只到命令输出
  • 显示的从顶部(头)100行只到从命令输出底部(尾部)100行
  • stdoutstderr归档为command.log.gz文件
  • 控制台输出必须相对实时显示,最终输出结果的解决方案是不可接受的,因为我们需要能够看到其执行进度。

当前发现

  • unbuffer可以用来强制标准输出/标准错误是无缓冲
  • |& tee可用于将输出发送到两个归档和尾/头
  • |& gzip --stdout >command.log.gz可以存档控制台输出
  • head -n100tail -n100可用于限制它们在控制台输出时的输出至少等不想要的结果的一些问题,如果输出线数为200
+0

'[-f command.log.gz] && gunzip command.log.gz; somecommand> tmp &&(($(wc -l 100))&& {head -n100 tmp; tail -n100 tmp;} || cat tmp; cat tmp >> command.log; gzip command.log; rm tmp' –

回答

0

这里下我的当前不全溶液,其为方便起见,显示出处理一个10行输出,这将(希望)第一限制输出到2行和最后两行。

#!/bin/bash 

seq 10 | tee >(gzip --stdout >output.log.gz) | tail -n2 
1

根据我的理解,您需要在线限制输出(在生成时)。 这是一个我能想到的功能,对你有用。

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_profile以在用户会话中加载。

使用示例:cat /var/log/messages | limit_output./configure | limit_output

功能将读取的标准输入,将其保存到日志文件,显示第一MAX线,然后在屏幕上每行减少到一个点,然后(。)最后显示最后的MAX行(如果输出短于MAX * 2,则输出更小)。