Help us understand the problem. What is going on with this article?

[Linux]自分のIPを変数に入れる方法

概要

シェルスクリプト内などで、自分の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

以上

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした