
私はそれからタイミング情報を抽出するさまざまな方法のいくつかの例を持っていますping -c 10 google.com
。これらのパイプの一部では、ping出力と同様に、時々出力ラインが生成されます。他の出力ラインでは、すべての出力ラインが処理された直後にすべての出力ラインが放出されます。最初の行動を見る時期と2番目の行動を見る時期を決める良いルールがありますか?
# prints output for each line as soon as it is received
# on OS X and Linux.
ping -c 10 google.com | grep -o 'time=\S*'
# prints output for each line as soon as it is received on OS X
# but not on Linux
# (the output of ping is slightly different so it's $8 on Linux to get the time)
ping -c 10 google.com | awk '{ print $7 }'
# waits until all input is received on OS X and Linux
ping -c 10 google.com | awk -F ':' '{ print $2 }'
# prints output for line as soon as it is received on Linux and OS X
ping -c 10 google.com | sed -e 's/^.*time=\(.*\) .*$/\1/'
# waits for the end of input on OS X and Linux
ping -c 10 google.com | grep -o 'time\S*' | sed -e 's/time=//'
# as a quick check, this prints each line of output immediately
# on OS X and Linux
ping -c 10 google.com | sed -e 's/time=//'
ツアーの後、これはラインバッファリングの問題に過ぎず、一部の標準ユーティリティは対話式で使用されている場合と非対話式で使用されている場合は異なる動作をするようです。
答え1
これらのプログラムでバッファリングを処理する方法についてです。
grepにパイプされたデータをすぐに出力させるには、--line-bufferedオプションと一緒にそれを使用します。
ping -c 10 google.com | grep --line-buffered -o 'time\S*' | sed -e 's/time=//'
awkがパイプデータをすぐに出力できるようにするには、-W Interactiveオプションを使用します。
ping -c 10 google.com | awk -W interactive '{ print $7 }'
詳細については、そのアプリケーションのマニュアルページを読んでください。
答え2
これらのバッファリングは、関連する記述子がttyでない場合、パイプによって実行されます。一部のコマンドには、これを処理して対話型の動作を適用する特定のオプションがあります。
この問題を解決する一般的な方法
あなたはそれを使用することができますstdbuf
GNU Coreutilsから。stdin
、stdout
およびのバッファリングを管理しますstderr
。に設定して完全に無効にするか、0
次に設定してラインバッファリングを有効にしますL
。
stdbuf -i0 -o0 -e0 command
stdbuf -oL ping example.com
このコマンドはsetvbuf()
ハッカー設定で機能しますLD_PRELOAD
。呼び出されたコマンドが強制的にその関数を再度呼び出すと、stdbuf
バッファリングが無効になることはありません。
また、使用することができますunbuffer
命令は本質的に同じ結果を得る。このコマンドはデフォルトで関連しており、インストールされていない可能性expect
があります。デフォルトでは、次のように使用できます。
unbuffer command
コマンド固有のオプション
コマンド固有のバッファリングに関して無効にする方法は次のとおりです。
grep
バッファリングを無効にするGNUオプション:--line-buffered
sed
バッファリングを無効にするGNUオプション:-u
awk
GNU は制御 tty がない場合はバッファリングしません。mawk
、少なくともDebian / Ubuntuのデフォルトawk、する出力バッファリング。mawk
可能使用できず、バッファリングを無効にするオプションをstdbuf
提供します。-Winteractive