Just a note: Since ifconfig typically displays more than one connection (in addition to the loopback connection), this code creates a single string variable with each IP address separated from the next by a newline. Mine looks like this:
bigbird@sananda:~/pq$ export IP=`/sbin/ifconfig | grep 'inet addr:'|\
grep -v '127.0.0.1'| cut -d: -f2 | awk '{print $1}'`
bigbird@sananda:~/pq$ echo "[${IP}]"
[192.168.126.1
192.168.114.1
192.168.1.2]
bigbird@sananda:~/pq$
To actually use this for something, it would probably have to parsed further (splitting the string on newlines).
One way to handle this would be to put the IP address strings into array elements to start with:
export IP=($(/sbin/ifconfig | grep 'inet addr:'|grep -v '127.0.0.1'| cut -d: -f2 |\
awk '{printf "%s ", $1}'))
for (( I=0; I<${#IP[@]}; I++ ))
do
echo "${I} [${IP[${I}]}]"
done
bigbird@sananda:~/bin$ mytest
0 [192.168.126.1]
1 [192.168.114.1]
2 [192.168.1.2]
bigbird@sananda:~/bin$
The added parens () turn the output into array elements.
The print has been changed to printf to add a blank (the default bash separator character) after each IP and to eliminate the newlines.
The back-tick notation:
`...`
for turning the output of a command into a string has also been replaced with newer syntax $(...) .
The for loop is included just to show the results and one way to access them.
/sbin/ifconfig | awk '/inet addr:/ { if ($2 !~ /:127./) { split($2, ip, ":") ; print ip[2] } }'– Torian Sep 8 '11 at 3:54