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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19224811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:12:26  来源:igfitidea点击:

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

linuxbashshellsedawk

提问by Ayush joshi

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 地址并写入我的脚本内容的文本

#!/bin/bash

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

eth0ip=$(ip addr | grep inet | grep eth0 | awk -F" " '{print }' | 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 

回答by Ed Morton

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. This:

让我们先清理你的代码。当您已经在使用 awk 时,您不需要十几个不同的命令和管道链。这个:

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

can be written simply as this:

可以简单地写成这样:

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

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 addrcommand, 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] = ; sub(/\/.*$/,"",ip[$NF]) }
END { print ( "eth0" in ip ? ip["eth0"] : ip["wlan0"] ) }
' > /home/pi/att/ip.txt

回答by Jotne

Here is a nice way to get your IP address. 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.

这是获取 IP 地址的好方法。这为您提供了在测试时用于访问互联网的地址,因此即使您从 Wifi 更改为 eth 或任何其他 IF 类型,它也会为您提供正确的 IP。

See more detailed post here: Linux bash script to extract IP address

在此处查看更详细的帖子:Linux bash script to extract IP address

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=" ")