简体   繁体   English

使用shell脚本(bash)查找特定接口的系统的IP地址

[英]find ip address of my system for a particular interface with shell script (bash)

I am trying to find ip-address of my own system through a shell script and write into a text thats my script content 我试图通过shell脚本找到我自己系统的ip-address并写入我脚本内容的文本

#!/bin/bash

wifiip=$(ip addr | grep inet | grep wlan0 | awk -F" " '{print $2}'| sed -e 's/\/.*$//')

eth0ip=$(ip addr | grep inet | grep eth0 | awk -F" " '{print $2}' | sed -e 's/\/.*$//')

if [ "$eth0ip" == "0" ]; then

    echo "$eth0ip" | grep [0-9]$ > /home/pi/att/ip.txt

else 

    echo "$wifiip" | grep [0-9]$ > /home/pi/att/ip.txt

fi

and trying to do something like if one interface is not up print another ip in ip.txt 并尝试做一些事情,如果一个接口没有在ip.txt中打印另一个IP

but it's giving 但它正在给予

ip.sh: 14: [: unexpected operator 

Let's clean up your code first. 让我们先清理你的代码。 You don't need chains of a dozen different commands and pipes when you're already using awk. 当你已经使用awk时,你不需要十几个不同命令和管道的链。 This: 这个:

wifiip=$(ip addr | grep inet | grep wlan0 | awk -F" " '{print $2}'| sed -e 's/\/.*$//')

can be written simply as this: 可以简单地写成:

wifiip=$(ip addr | awk '/inet/ && /wlan0/{sub(/\/.*$/,"",$2); print $2}')

but your whole script can be written as just one awk command. 但是你的整个脚本只能写成一个awk命令。

I need you to update your question with some sample output of the ip addr command, the output you want from the awk command given that input, and explain more clearly what you're trying to do in order to show you the correct way to write that but it might be something like this: 我需要你用ip addr命令的一些示例输出来更新你的问题,给出输入你想要的awk命令的输出,并更清楚地解释你想要做什么,以便向你展示正确的写法但它可能是这样的:

ip addr | awk '
/inet/ { ip[$NF] = $2; sub(/\/.*$/,"",ip[$NF]) }
END { print ( "eth0" in ip ? ip["eth0"] : ip["wlan0"] ) }
' > /home/pi/att/ip.txt

Here is a nice way to get your IP address. 这是获取IP地址的好方法。 This gives you the address used to reach the internet at the test, so it will give you correct IP even if you change from Wifi to eth or to any other IF type. 这为您提供了在测试时用于访问互联网的地址,因此即使您从Wifi更改为eth或任何其他IF类型,它也会为您提供正确的IP。

See more detailed post here: Linux bash script to extract IP address 在这里查看更详细的帖子: Linux bash脚本提取IP地址

my_ip=$(ip route get 8.8.8.8 | awk '/8.8.8.8/ {print $NF}')

To get interface name: 获取接口名称:

my_if=$(ip route get 8.8.8.8 | awk '/dev/ {f=NR} f&&NR-1==f' RS=" ")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM