#!/bin/bash getip() { AF= DEV= while getopts "46d:" OPT "$@" #can't rely on $0 since it's global do case $OPT in 4|6 ) AF="-${OPT}" ;; d ) DEV=$OPTARG ;; esac done IP=$(which ip) if [[ -x $IP ]]; then if ip ${AF} addr show $DEV >/dev/null 2>/dev/null then # Probably using IPROUTE2 tools # ...I remember a long time ago, a version of ip that doesn't support -o if ip -o ${AF} addr show $DEV >/dev/null 2>/dev/null then ip -o ${AF} addr show $DEV | while read A B C D E do if [[ ${C} =~ inet6? ]] #no quotes! then echo ${D%/*} fi done else ip ${AF} addr show $DEV | while read A B C do if [[ ${A} =~ inet6? ]] #no quotes! then echo ${B%/*} fi done fi fi else IFCFG=$(which ifconfig) if [[ -x $IFCFG ]]; then # Probably using NET-3 tools # At least two documented variants ifconfig $DEV | while read A B C D do if [[ ( -z ${AF} || ${AF} == '-4' ) && ${A} == 'inet' ]] then echo ${B#addr:} else if [[ ( -z ${AF} || ${AF} == '-6' ) && ${A} == 'inet6' ]] then echo ${C%/*} fi fi done else echo "Neither ip nor ifconfig are available; bailing." >/dev/stderr exit -1 fi fi } #examples: getip -4 -d eth0 getip -d lo -6 # vim:set ts=4 sw=4 ai si: