LoginSignup
9
8

More than 5 years have passed since last update.

スクリプト内でIPアドレスを取得するときに使用する書き方

Last updated at Posted at 2015-12-21

以下、eth0 に割り当てられているIPv4 アドレスを取得する際に使う書き方です。

/sbin/ip -f inet -o addr show eth0 | awk '( $9 == "eth0" ) {print $4}' | cut -d/ -f 1

[解説]

/sbin/ip -f inet -o addr show で、以下のような出力が得られる。

2: eth0 inet 192.168.1.1/24 brd 10.52.1.191 scope global eth0

NIC に複数のIPが振られていると、

2: eth0 inet 192.168.1.1/24 brd 10.52.2.255 scope global eth0
2: eth0 inet 192.168.1.2/24 brd 10.52.2.255 scope global secondary eth0:1

というように、複数行出てくるので、

awk '( $9 == "eth0" ) {print $4}'

で、$9 が eth0 である行のみを抽出し、print $4
"192.168.1.1/24" という文字列が取得できる。

cut -d/ -f 1

cut コマンドで区切り文字を '/' とし、192.168.1.1 と 24 で分割し、1番目を取り出す。

サンプルとして、eth0 / eth1 を取得して変数に代入するshellスクリプト

ipaddr.sh
IF_ETH0=`/sbin/ip -f inet -o addr show eth0 | awk '( $9 == "eth0" ) {print $4}' | cut -d/ -f 1`
IF_ETH1=`/sbin/ip -f inet -o addr show eth1 | awk '( $9 == "eth1" ) {print $4}' | cut -d/ -f 1`
9
8
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
9
8