Linux 標準出力をファイルに書き込む

Linux 標準出力をファイルに書き込む

Linuxで、標準出力をファイルに書き込む手順を記述してます。

環境

  • OS Rocky Linux release 8.4 (Green Obsidian)

標準出力をファイルに書き込む

標準出力をファイルに書き込むには、「 tee 」コマンドを使用します。

例えば「ping」の実行結果を、ファイル「ping.log」に書き込む場合は、以下のようにします。

ping 8.8.8.8 | tee ping.log

<出力結果>
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=44.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=38.3 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=38.1 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=116 time=45.4 ms

※「ctrl + c」で停止

ファイルに書き込まれているか確認してみます。

cat ping.log

<出力結果>
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=44.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=38.3 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=38.1 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=116 time=45.4 ms

標準出力に表示された結果が書き込みされていることが確認できます。

オプション「-a」を使用するとファイルに追記することができます。

ping 8.8.8.8 | tee -a ping.log

<出力結果>
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=46.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=69.4 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=56.2 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=116 time=50.10 ms
64 bytes from 8.8.8.8: icmp_seq=5 ttl=116 time=69.4 ms

追記されていることが確認できます。

cat ping.log

<出力結果>
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=44.6 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=38.3 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=38.1 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=116 time=45.4 ms
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=116 time=46.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=116 time=69.4 ms
64 bytes from 8.8.8.8: icmp_seq=3 ttl=116 time=56.2 ms
64 bytes from 8.8.8.8: icmp_seq=4 ttl=116 time=50.10 ms
64 bytes from 8.8.8.8: icmp_seq=5 ttl=116 time=69.4 ms

複数のファイルに書き出し

以下のように複数のファイルに書き出すことも可能です。

ping 8.8.8.8 | tee ping.log ping2.log