linux - find ip address of my system for a paticular interface with shell script (bash) -


i trying find ip-address of own system through shell script , write text thats 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" ];      echo "$eth0ip" | grep [0-9]$ > /home/pi/att/ip.txt  else       echo "$wifiip" | grep [0-9]$ > /home/pi/att/ip.txt  fi 

and trying if 1 interface not print ip in ip.txt

but giving

ip.sh: 14: [: unexpected operator  

let's clean code first. don't need chains of dozen different commands , pipes when you're using awk. this:

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

can written this:

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

but whole script can written 1 awk command.

i need update question sample output of ip addr command, output want awk command given input, , explain more you're trying in order show correct way write might 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 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -