最初に結論
hostname -I
を使うと良い
某所で、自ホストのIPアドレスを取得するためにこんなことをしている箇所を見つけたのが発端です。
LANG=C /sbin/ifconfig | grep 'inet addr' | awk '{print $2;}' | cut -d: -f2 | grep -v 127.0.0.1 | tail -n 1
もう少し、簡潔にできないかなー。(そもそもifconfigはもう使わない方が良いし) ip addr show eht0
とかでもデータ加工しないとだめだしな。とか考えてたら、hostname
でできそうだということが分かりました。
似たオプションで、-i
と-I
があるのですが、名前解決ができるかできないかの違いです。用途に合わせて使い分けましょう。
-i, --ip-address
Display the network address(es) of the host name. Note that this works only if the
host name can be resolved. Avoid using this option; use hostname --all-ip-addresses
instead.
-I, --all-ip-addresses
Display all network addresses of the host. This option enumerates all configured
addresses on all network interfaces. The loopback interface and IPv6 link-local
addresses are omitted. Contrary to option -i, this option does not depend on name res‐
olution. Do not make any assumptions about the order of the output.
LANG=C /sbin/ifconfig | grep 'inet addr' | awk '{print $2;}' | cut -d: -f2 | grep -v 127.0.0.1 | tail -n 1
闇感ある。
— masasuzu.lab (@masasuz) February 1, 2016
hostname -I | head -1
かなー。場合に依るけど。
— masasuzu.lab (@masasuz) February 1, 2016
hostname -I と hostname -i の違いを覚えた。
— masasuzu.lab (@masasuz) February 1, 2016