Files
dougal-software/sbin/get-ip.sh

20 lines
617 B
Bash
Raw Normal View History

#!/bin/bash
# Find the interface used for the default route (e.g., to reach 8.8.8.8)
INTERFACE=$(ip route get 8.8.8.8 | awk '{for(i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}')
if [ -z "$INTERFACE" ] || [ "$INTERFACE" = "lo" ]; then
echo "No valid default route found." >/dev/stderr
exit 1
fi
# Extract the primary IPv4 address from the interface (excluding loopback)
IP=$(ip -4 addr show dev "$INTERFACE" scope global | grep -oP '(?<=inet\s)\d{1,3}(\.\d{1,3}){3}(?=/)' | head -n1)
if [ -z "$IP" ]; then
echo "No global IPv4 address found on $INTERFACE." >/dev/stderr
exit 1
fi
echo "$IP"