I think pinging $(hostname) is not a good solution either, because it also relies on something that does not have to exist (e.g. hostname may not resolve into anything). The following command finds all non-local IP addresses associated with network interfaces.
/sbin/ifconfig | sed -e '/./{H;$!d};x;/LOOPBACK/d;/inet addr:.\+ UP [ A-Z]\+RUNNING/!d;s/.*inet addr:\([0-9.]\+\).*/\1/'
'| head -1' can be appended to automatically choose the first IP address. However as ifconfig is begin deprecated, it might be a good idea to use /sbin/ip instead.
I think pinging $(hostname) is not a good solution either, because it also relies on something that does not have to exist (e.g. hostname may not resolve into anything). The following command finds all non-local IP addresses associated with network interfaces.
/sbin/ifconfig | sed -e '/./{H; $!d};x; /LOOPBACK/ d;/inet addr:.\+ UP [ A-Z]\+RUNNING/ !d;s/.* inet addr:\( [0-9.]\ +\).*/\ 1/'
'| head -1' can be appended to automatically choose the first IP address. However as ifconfig is begin deprecated, it might be a good idea to use /sbin/ip instead.