找到我的系统的IP地址与shell脚本中paticular接口(庆典) [英] find ip address of my system for a paticular interface with shell script (bash)

查看:185
本文介绍了找到我的系统的IP地址与shell脚本中paticular接口(庆典)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过一个shell脚本找到我自己的系统的IP地址,并写入一个文本这就是我的剧本内容

 #!/斌/庆典wifiip = $(IP地址| grep的INET | grep的为wlan0 | awk的-F'{$打印2}| sed的-e的/\\/.*$//')eth0ip = $(IP地址| grep的INET | grep的eth0的| awk的-F'{$打印2}| sed的-e的/\\/.*$//')如果[$ eth0ip==0];然后    回声$ eth0ip| grep的[0-9] $> /home/pi/att/ip.txt其他    回声$ wifiip| grep的[0-9] $> /home/pi/att/ip.txt科幻

和试图做一些事情一样,如果一个接口不起来打印ip.txt另一个IP

但其捐赠

  ip.sh:14:[:意外的运营商


解决方案

让我们先来清理你的code。当你已经在使用AWK你并不需要十几个不同的命令和管道链。这样的:

  wifiip = $(IP地址| grep的INET | grep的为wlan0 | awk的-F'{$打印2}| sed的-e的/\\/.*$// ')

可以简单地写成这样:

  wifiip = $(IP地址| awk的'/ INET /&放大器;&安培; /wlan0/{sub(/\\/.*$/,\"\",$2);打印$ 2 })

但你的整个脚本可以写成只是一个awk命令。

我需要你的 IP地址命令的输出示例,从awk命令你想要的输出来更新你的问题给出了输入,并解释清楚什么你想,以你展示编写正确的方式做,但它可能是这样的:

  IP地址| AWK
/ INET / {IP [$ NF] = $ 2;子(/\\/.*$/,,IP [$ NF])}
END {打印(在IPeth0的IP [eth0的]:IP [为wlan0])}
'> /home/pi/att/ip.txt

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

and trying to do something like if one interface is not up print another ip in ip.txt

but its 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. 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.

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

这篇关于找到我的系统的IP地址与shell脚本中paticular接口(庆典)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆