2017-04-24 24 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,則輸出更小)。