Skip to content

Instantly share code, notes, and snippets.

@orlissenberg
Last active August 29, 2015 14:10
Show Gist options
  • Save orlissenberg/5ebecf1762f5be980527 to your computer and use it in GitHub Desktop.
Save orlissenberg/5ebecf1762f5be980527 to your computer and use it in GitHub Desktop.
Fetch IPv4 address from ifconfig with awk shell script.
#!/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 $?;
@orlissenberg
Copy link
Author

real 0m0.005s
user 0m0.003s
sys 0m0.002s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment