前言
linux的shell中如何获取服务器的IP地址
内容
ip a | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}'| awk -F "/" '{print $1}'
- 我们先
ip a
查看IP相关信息
[root@tb_scrm_service_kafka_3 bin]# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN qlen 1 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host valid_lft forever preferred_lft forever 2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP qlen 1000 link/ether fa:16:3e:e8:c8:bb brd ff:ff:ff:ff:ff:ff inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0 valid_lft 70598sec preferred_lft 70598sec inet6 fe80::f816:3eff:fee8:c8bb/64 scope link noprefixroute valid_lft forever preferred_lft forever
- 通过
grep
来筛选除有用的信息
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet inet 127.0.0.1/8 scope host lo inet6 ::1/128 scope host inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0 inet6 fe80::f816:3eff:fee8:c8bb/64 scope link noprefixroute
- 通过
grep
去除无用的信息
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 inet 127.0.0.1/8 scope host lo inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0
- 通过
grep
,再来一次去除一次无用信息
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 | grep -v '127.0.0.1' inet 192.168.1.86/24 brd 192.168.1.255 scope global noprefixroute dynamic eth0
- 通过
awk
打印第二列内容,即IP地址
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 | grep -v '127.0.0.1' | awk '{print $2}' 192.168.1.86/24
- 通过
awk
分割并打印
[root@tb_scrm_service_kafka_3 bin]# ip a | grep inet | grep -v inet6 | grep -v '127.0.0.1' | awk '{print $2}' | awk -F '/' '{print $1}' 192.168.1.86
学无止境,谦卑而行.