Obtain the local ip address in the Shell script, and Linux obtains the local ip address

There are many ways to obtain the IP address of the local machine in the Shell script. Here are three commonly used methods:

1. Use the ifconfig command to obtain the local IP address

The ifconfig command can obtain the configuration information of the local network card, including the IP address. You can use the grep command to filter out the IP address information, and then use the awk command to extract the specific IP address. The sample code is as follows:

ip=$(ifconfig | grep -E 'inet [0-9]' | awk '{print $2}')
echo "本机 IP 地址为:$ip"

2. Use the hostname command to obtain the local IP address

The hostname command can obtain the host name of the machine, and the IP address corresponding to the host name can be obtained by adding the -I parameter. The sample code is as follows:

ip=$(hostname -I)
echo "本机 IP 地址为:$ip"

3. Use the ip command to obtain the local IP address

The ip command is a substitute for the ifconfig command, which can obtain the configuration information of the local network card, including the IP address. Use the ip addr show command to obtain the information of all network cards, then use the grep command to filter out the IP address information, and finally use the awk command to extract the specific IP address. The sample code is as follows:

ip=$(ip addr show | grep -E 'inet [0-9]' | awk '{print $2}' | awk -F '/' '{print $1}')
echo "本机 IP 地址为:$ip"

The above three methods can be used to obtain the IP address of the machine in the Shell script, and the appropriate method can be selected according to the actual situation.

Guess you like

Origin blog.csdn.net/weixin_42279822/article/details/130641014