Tips when you want to put your IP in a variable, such as in a shell script Only IPv4 is supported.
$ 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 #Show only eth0
192.168.1.1
$ hostname -I #Show everything except lo
192.168.1.1 192.168.2.1
#The simplest way
$ MyIP=`hostname -i`
$ echo $MyIP
192.168.1.1
#When there are multiple IPs
$ MyIPeth0=`hostname -I | cut -f1 -d' '`
$ echo $MyIPeth0
192.168.1.1
$ MyIPeth1=`hostname -I | cut -f2 -d' '`
$ echo $MyIPeth1
192.168.2.1
Click here if you are told to use the hostname command because it is dangerous
$ 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
When executing the hostname command as root, if'hostname i'is used instead of'hostname -i' Note that the host name will be 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
that's all
Recommended Posts