Files
drunkendotfiles/.local/bin/tmux-ip
dissimulo 467b967ced tmux-ip: portable local-IP fallback for macOS
`hostname -I` is GNU-only and errors on BSD/macOS, so when the public-IP
curl couldn't reach api.ipify.org the script printed nothing and the
tmux status bar showed an empty IP. Try `ipconfig getifaddr` for common
interfaces first, fall back to `hostname -I` on Linux, then `ifconfig`
as a last resort. Also guard against empty-but-zero-exit curl output.
2026-05-17 03:12:11 -07:00

50 lines
1.3 KiB
Bash
Executable File

#!/bin/bash
#
# Print the "best" IP for the tmux status bar.
# Preference: DO reserved/floating IP > public egress (ipify) > first local IP.
#
set -u
META="http://169.254.169.254/metadata/v1"
CURL="curl -sf --connect-timeout 1 --max-time 2"
is_digitalocean() {
[ -r /sys/class/dmi/id/sys_vendor ] \
&& grep -qi digitalocean /sys/class/dmi/id/sys_vendor
}
do_anchor_ip() {
local kind active ip
for kind in reserved_ip floating_ip; do
active=$($CURL "$META/$kind/ipv4/active" 2>/dev/null) || continue
[ "$active" = "true" ] || continue
ip=$($CURL "$META/$kind/ipv4/ip_address" 2>/dev/null) || continue
[ -n "$ip" ] && { printf '%s\n' "$ip"; return 0; }
done
return 1
}
if is_digitalocean && do_anchor_ip; then
exit 0
fi
print_local_ip() {
local iface ip
if command -v ipconfig >/dev/null 2>&1; then
for iface in en0 en1 en2; do
ip=$(ipconfig getifaddr "$iface" 2>/dev/null) || true
[ -n "${ip:-}" ] && { printf '%s\n' "$ip"; return 0; }
done
fi
if hostname -I >/dev/null 2>&1; then
hostname -I | awk '{print $1}'
return 0
fi
ifconfig 2>/dev/null | awk '/inet /{ if ($2 != "127.0.0.1") { print $2; exit } }'
}
ip=$(curl -s --connect-timeout 3 https://api.ipify.org 2>/dev/null || true)
[ -z "${ip:-}" ] && ip=$(print_local_ip)
printf '%s\n' "${ip:-}"