Reputation: 10122
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
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
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
Reputation: 31
May be this could help.
more /etc/hosts | grep `hostname` | awk '{print $1}'
Upvotes: 0
Reputation: 189
ifconfig | grep 'broadcast\|Bcast' | awk -F ' ' {'print $2'} | head -n 1 | sed -e 's/addr://g'
Upvotes: 0
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
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
Reputation: 1079
you give direct interface thereby reducing one grep.
ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'
Upvotes: 5