Skip to content

Instantly share code, notes, and snippets.

@robert-mcdermott
Last active March 21, 2026 02:29
Show Gist options
  • Select an option

  • Save robert-mcdermott/770883d4d8c1a75ee1653c07e79ee128 to your computer and use it in GitHub Desktop.

Select an option

Save robert-mcdermott/770883d4d8c1a75ee1653c07e79ee128 to your computer and use it in GitHub Desktop.
mac-network-sleeper-setup.sh - automatically disable network on sleep and reenable on wake
#!/bin/zsh
set -euo pipefail
echo "Checking Homebrew..."
if ! command -v brew >/dev/null 2>&1; then
echo "Homebrew not found. Installing it for Apple silicon..."
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
eval "$(/opt/homebrew/bin/brew shellenv)"
else
# Prefer the Apple silicon Homebrew path if present
if [ -x /opt/homebrew/bin/brew ]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
fi
fi
echo "Using brew at: $(command -v brew)"
echo "Detecting Wi-Fi interface..."
WIFI_DEVICE="$(networksetup -listallhardwareports | awk '
/Hardware Port: Wi-Fi/ { found=1; next }
found && /Device:/ { print $2; exit }
')"
if [ -z "${WIFI_DEVICE:-}" ]; then
echo "Could not detect the Wi-Fi interface."
echo "Run: networksetup -listallhardwareports"
exit 1
fi
echo "Wi-Fi interface detected: $WIFI_DEVICE"
echo "Installing sleepwatcher..."
brew install sleepwatcher
echo "Writing ~/.sleep ..."
cat > "$HOME/.sleep" <<EOF
#!/bin/zsh
FLAG="\$HOME/.sleepwatcher-wifi-managed"
# Only turn off (and set flag) if Wi-Fi is currently on
if /usr/sbin/networksetup -getairportpower ${WIFI_DEVICE} | grep -q 'On'; then
echo "\$(date) sleep: turning Wi-Fi off on ${WIFI_DEVICE}" >> "\$HOME/sleepwatcher-wifi.log"
/usr/sbin/networksetup -setairportpower ${WIFI_DEVICE} off >> "\$HOME/sleepwatcher-wifi.log" 2>&1
touch "\$FLAG"
else
echo "\$(date) sleep: Wi-Fi already off (manually), leaving it off" >> "\$HOME/sleepwatcher-wifi.log"
fi
EOF
echo "Writing ~/.wakeup ..."
cat > "$HOME/.wakeup" <<EOF
#!/bin/zsh
FLAG="\$HOME/.sleepwatcher-wifi-managed"
# Only restore Wi-Fi if the sleep script was the one that turned it off
if [ -f "\$FLAG" ]; then
echo "\$(date) wake: turning Wi-Fi on on ${WIFI_DEVICE}" >> "\$HOME/sleepwatcher-wifi.log"
/usr/sbin/networksetup -setairportpower ${WIFI_DEVICE} on >> "\$HOME/sleepwatcher-wifi.log" 2>&1
rm -f "\$FLAG"
else
echo "\$(date) wake: Wi-Fi was manually off, leaving it off" >> "\$HOME/sleepwatcher-wifi.log"
fi
EOF
chmod +x "$HOME/.sleep" "$HOME/.wakeup"
echo "Restarting sleepwatcher service..."
brew services restart sleepwatcher
echo
echo "Done."
echo "Wi-Fi interface: $WIFI_DEVICE"
echo "Service status:"
brew services list | grep sleepwatcher || true
echo
echo "Current Wi-Fi power state:"
networksetup -getairportpower "$WIFI_DEVICE" || true
echo
echo "Log file:"
echo "$HOME/sleepwatcher-wifi.log"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment