LoginSignup
18
20

More than 5 years have passed since last update.

pingに日時(タイムスタンプ)をつける

Last updated at Posted at 2017-03-23

私が自分で気に入っているpingに日時(タイムスタンプ)をつけるコマンドは以下のとおりです。理由は短いからです。

$ ping localhost | xargs -I_ date +'%c _'

結果はこんな感じです。

Thu Mar 23 17:32:01 2017 PING localhost (127.0.0.1) 56(84) bytes of data.
Thu Mar 23 17:32:02 2017 64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.087 ms
Thu Mar 23 17:32:02 2017 64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.070 ms
Thu Mar 23 17:32:03 2017 64 bytes from localhost (127.0.0.1): icmp_req=3 ttl=64 time=0.077 ms
Thu Mar 23 17:32:04 2017 64 bytes from localhost (127.0.0.1): icmp_req=4 ttl=64 time=0.070 ms
Thu Mar 23 17:32:05 2017 64 bytes from localhost (127.0.0.1): icmp_req=5 ttl=64 time=0.074 ms
Thu Mar 23 17:32:06 2017 64 bytes from localhost (127.0.0.1): icmp_req=6 ttl=64 time=0.074 ms
Thu Mar 23 17:32:07 2017 64 bytes from localhost (127.0.0.1): icmp_req=7 ttl=64 time=0.071 ms

日時フォーマットについて

日本語の環境の場合は日時の部分が「2017年03月23日 17時32分01秒」のように日本語になってしまうので、それが嫌な場合は事前にLANG=Cとしておくか、以下のようにコマンドの中にLANG=Cを挟み込みます。

$ ping localhost | LANG=C xargs -I_ date +'%c _'

また%cのところを%F %Tのようにすれば以下のように表示することもできます。UNIXとかに慣れていない方はこちらの方が馴染みやすいかもしれません。

$ ping localhost | xargs -I_ date +'%F %T _'
2017-03-23 17:38:15 PING localhost (127.0.0.1) 56(84) bytes of data.
2017-03-23 17:38:15 64 bytes from localhost (127.0.0.1): icmp_req=1 ttl=64 time=0.078 ms
2017-03-23 17:38:16 64 bytes from localhost (127.0.0.1): icmp_req=2 ttl=64 time=0.078 ms
2017-03-23 17:38:17 64 bytes from localhost (127.0.0.1): icmp_req=3 ttl=64 time=0.070 ms
2017-03-23 17:38:18 64 bytes from localhost (127.0.0.1): icmp_req=4 ttl=64 time=0.073 ms
2017-03-23 17:38:19 64 bytes from localhost (127.0.0.1): icmp_req=5 ttl=64 time=0.072 ms
2017-03-23 17:38:20 64 bytes from localhost (127.0.0.1): icmp_req=6 ttl=64 time=0.074 ms

xargsの-Iオプションについて

xargsを使ったサンプルで-I-L 1を同時に指定しているのをよく見かけるのですが、-Iオプションのヘルプを読むとImplies -x and -L 1とあるので私は-L 1は指定していません。もし挙動がおかしいとかの場合、指定してみると変わるのかもしれません。

結果を保存するには

pingの結果を保存するには以下のような感じでteeコマンドを使うのがシンプルで分かりやすいかなと思います。

teeコマンド
$ ping localhost | xargs -I_ date +'%c _' | tee localhost.txt
18
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
20