Last active
August 29, 2015 14:10
-
-
Save orlissenberg/5ebecf1762f5be980527 to your computer and use it in GitHub Desktop.
Fetch IPv4 address from ifconfig with awk shell script.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Examples: | |
# ./fetch_ip.sh "" docker | |
# ./fetch_ip.sh "" lo | |
# ./fetch_ip.sh 192.168 | |
# ./fetch_ip.sh 192.168 eth1 | |
ifconfig | awk '{ | |
if ($0 ~ /Link encap:/ && $0 ~ /'$2'/) { | |
if ((getline tmp) > 0) { | |
where = match(tmp, /inet addr:[0-9\.]*/); | |
if (where) { | |
if (substr(tmp, where + 10, RLENGTH - 10) ~ /'$1'/) { | |
print substr(tmp, where + 10, RLENGTH - 10); | |
f=1; exit; | |
} | |
} | |
} | |
} | |
} | |
END { exit !f; }'; | |
# single line, no script | |
# ifconfig | awk -v ip="192" -v interface="eth2" '{ if ($0 ~ /Link encap:/ && $0 ~ interface) { if ((getline tmp) > 0) { where = match(tmp, /inet addr:[0-9\.]*/); if (where) { if (substr(tmp, where + 10, RLENGTH - 10) ~ ip) { print substr(tmp, where + 10, RLENGTH - 10); f=1; exit; }}}}} END { exit !f; }' | |
# Test exit status. | |
# echo $?; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
real 0m0.005s
user 0m0.003s
sys 0m0.002s