Shell脚本获取本机IP并将IP赋值给变量待用

方法一

1
2
3
4
#!/bin/bash
ETH="eth0"
HOST_IP=$(ifconfig $ETH | grep "inet" | awk '{ print $2}' | awk -F: '{print $2}')
echo $HOST_IP

注:该方法会将ipv6地址一并获取

方法二

1
2
3
#!/bin/bash
HOST_IP=$(ifconfig eth0 | grep "netmask" | awk '{ print $2 }')
echo $HOST_IP