Eric Platon
Eric Platon

Reputation: 10122

Efficient way to get your IP address in shell scripts

Context: On *nix systems, one may get the IP address of the machine in a shell script this way:

ifconfig | grep 'inet' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}'

Or this way too:

ifconfig | grep 'inet' | grep -v '127.0.0.1' | awk '{print $2}' | sed 's/addr://'

Question: Would there be a more straightforward, still portable, way to get the IP address for use in a shell script?

(my apologies to *BSD and Solaris users as the above command may not work; I could not test)

Upvotes: 11

Views: 27522

Answers (7)

Ahmad Yoosofan
Ahmad Yoosofan

Reputation: 981

Based on this you can use the following command

ip route get 8.8.8.8 | awk 'NR==1 {print $NF}'

Upvotes: 3

figtrap
figtrap

Reputation: 154

# for bash/linux
ipaddr(){
if="${1:-eth0}"
result=$(/sbin/ip -o -4 addr show dev "${if}" | sed 's/^.*inet // ; s/\/...*$//')
printf %s "${result}"
tty -s  && printf "\n"
}

Upvotes: 0

Gautham Shervegar
Gautham Shervegar

Reputation: 31

May be this could help.

 more /etc/hosts | grep `hostname` | awk '{print $1}'

Upvotes: 0

David J Merritt
David J Merritt

Reputation: 189

ifconfig | grep 'broadcast\|Bcast' | awk -F ' ' {'print $2'} | head -n 1 | sed -e 's/addr://g'

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342353

you can do it with just one awk command. No need to use too many pipes.

$ ifconfig | awk -F':' '/inet addr/&&!/127.0.0.1/{split($2,_," ");print _[1]}'

Upvotes: 12

t0mm13b
t0mm13b

Reputation: 34592

Look here at the Beej's guide to networking to obtain the list of sockets using a simple C program to print out the IP addresses using getaddrinfo(...) call. This simple C Program can be used in part of the shell script to just print out the IP addresses available to stdout which would be easier to do then rely on the ifconfig if you want to remain portable as the output of ifconfig can vary.

Hope this helps, Best regards, Tom.

Upvotes: 1

coder
coder

Reputation: 1079

you give direct interface thereby reducing one grep.

ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'

Upvotes: 5

Related Questions