Ayush joshi Ayush joshi - 7 months ago 14
Bash Question

find ip address of my system for a paticular 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

#!/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

Answer

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