使用shell脚本(bash)查找特定接口的系统IP地址 [英] find ip address of my system for a particular interface with shell script (bash)
问题描述
我正在尝试通过Shell脚本查找自己系统的ip地址,并将其写入脚本内容
I am trying to find ip-address of my own system through a shell script and write into a text thats my script content
#!/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
并尝试执行某些操作(如果一个接口未启动),则在ip.txt中打印另一个ip
and trying to do something like if one interface is not up print another ip in ip.txt
但它给出了
ip.sh: 14: [: unexpected operator
推荐答案
让我们先清理您的代码.当您已经在使用awk时,不需要十几个不同的命令和管道链.这个:
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:
wifiip=$(ip addr | grep inet | grep wlan0 | awk -F" " '{print $2}'| sed -e 's/\/.*$//')
可以简单地写成这样:
wifiip=$(ip addr | awk '/inet/ && /wlan0/{sub(/\/.*$/,"",$2); print $2}')
但是您的整个脚本可以只写为一个awk命令.
but your whole script can be written as just one awk command.
我需要您使用ip addr
命令的一些示例输出,给定该输入的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 '
/inet/ { ip[$NF] = $2; sub(/\/.*$/,"",ip[$NF]) }
END { print ( "eth0" in ip ? ip["eth0"] : ip["wlan0"] ) }
' > /home/pi/att/ip.txt
这篇关于使用shell脚本(bash)查找特定接口的系统IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!