概要
シェルスクリプト内などで、自分のIPを変数に入れたい場合のTips
IPv4のみ対応です。
環境
$ cat /etc/os-release
NAME="Amazon Linux"
VERSION="2"
ID="amzn"
ID_LIKE="centos rhel fedora"
VERSION_ID="2"
PRETTY_NAME="Amazon Linux 2"
ANSI_COLOR="0;33"
CPE_NAME="cpe:2.3:o:amazon:amazon_linux:2"
HOME_URL="https://amazonlinux.com/"
$ ip a|grep -e inet |grep -v inet6
inet 127.0.0.1/8 scope host lo
inet 192.168.1.1/24 brd 192.168.1.255 scope global dynamic eth0
inet 192.168.2.1/24 brd 192.168.2.255 scope global dynamic eth1
$ hostname -i #eth0のみ表示
192.168.1.1
$ hostname -I #loを除く全てを表示
192.168.1.1 192.168.2.1
コマンド
# 一番シンプルな方法
$ MyIP=`hostname -i`
$ echo $MyIP
192.168.1.1
# IPが複数ある場合
$ MyIPeth0=`hostname -I | cut -f1 -d' '`
$ echo $MyIPeth0
192.168.1.1
$ MyIPeth1=`hostname -I | cut -f2 -d' '`
$ echo $MyIPeth1
192.168.2.1
コマンド2
hostnameコマンドは危険だから使うなって言われた場合はこちら
$ MyIPeth0=`ip -f inet -o addr show eth0|cut -d\ -f 7 | cut -d/ -f 1`
$ echo $MyIPeth0
192.168.1.1
$ MyIPeth1=`ip -f inet -o addr show eth1|cut -d\ -f 7 | cut -d/ -f 1`
$ echo $MyIPeth1
192.168.2.1
補足
rootでhostnameコマンド実行時、'hostname -i'とするところを'hostname i'とすると
ホスト名がiになるので注意。
$ hostname
hogehoge
$ hostname i
hostname: you must be root to change the host name
$ sudo su -
#
# hostname i
# hostname
i
# MyIPeth0=`hostname I | cut -f1 -d' '`
# hostname
I
以上