Skip to content

Instantly share code, notes, and snippets.

@riywo
Created March 17, 2011 08:37
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save riywo/874011 to your computer and use it in GitHub Desktop.
Save riywo/874011 to your computer and use it in GitHub Desktop.
bashでパイプとかでつないでバッファされちゃう時

tail -fみたいに流しながら見たいんだけど、色んなコマンドが出力をバッファしちゃうので、困ったときはそのコマンドにバッファしないオプションが無いか探すのがオヌヌメ。 man command -> bufferとかで検索

grep

   --line-buffered
          Use line buffering, it can be a performance penality.

$ iostat -x 1 | grep --line-buffered 'sda'

awk

   fflush([file])        Flush any buffers associated with the open output file or pipe file.  If file is missing, then standard output is flushed.  If  file
                         is the null string, then all open output files and pipes have their buffers flushed.

$ vmstat 1 | awk '{print $1}{fflush()}'

mysql

   ?   --unbuffered, -n

       Flush the buffer after each query.

$ mysql -n -uroot -e "SQL"

※あまり使う場面が思いつかなかったですが、少なくともfork & execでSTDOUTとか継続して使おうとした時に必要でした。

perl

普通にprint STDOUT "hogehoge"とかするとteeに噛ませるとバッファされる。

$| = 1;

$ hoge.pl | tee /tmp/log

while : ; do
grep eth0 /proc/net/dev | cut -f2- -d:
sleep 1
done | awk ' \
NR > 1{print strftime("%Y/%m/%d %H:%H:%S"), ($1 - old_in)*8/1024/1024, ($9 - old_out)*8/1024/1024} \
{old_in = $1; old_out = $9; fflush()} \
' | tee /tmp/traffic.log
@riywo
Copy link
Author

riywo commented Mar 17, 2011

あんま関係ないけど、ifstatをawkでやるとこんな感じ、ってのでteeでログ吐く場合はfflushしてあげないとSTDOUTに出てこない。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment