Skip to content

Instantly share code, notes, and snippets.

@u1i
Created September 25, 2024 02:12
Show Gist options
  • Save u1i/27c5a77118df7b0c164038d111b02274 to your computer and use it in GitHub Desktop.
Save u1i/27c5a77118df7b0c164038d111b02274 to your computer and use it in GitHub Desktop.
MacOs forget and reconnect Wifi
#!/bin/bash
# Variables
SSID="Skynet"
PASSWORD="test12345678"
# Ensure network interface is correct; change `en0` if necessary
INTERFACE="en0"
function debug_message() {
echo "DEBUG: $1"
}
debug_message "Turning off the Wi-Fi interface..."
/usr/sbin/networksetup -setairportpower $INTERFACE off
sleep 5
debug_message "Wi-Fi interface is turned off. Forgetting the network $SSID..."
/usr/sbin/networksetup -removepreferredwirelessnetwork $INTERFACE "$SSID"
debug_message "Network $SSID is forgotten."
debug_message "Turning on the Wi-Fi interface..."
/usr/sbin/networksetup -setairportpower $INTERFACE on
sleep 5
debug_message "Wi-Fi interface is turned on. Reconnecting to the network $SSID..."
/usr/sbin/networksetup -setairportnetwork $INTERFACE "$SSID" "$PASSWORD"
debug_message "Reconnection command sent to $SSID."
current_network=$(/usr/sbin/networksetup -getairportnetwork $INTERFACE)
debug_message "Current network status: $current_network"
if [[ $current_network == *"$SSID"* ]]; then
debug_message "Successfully connected to $SSID."
else
debug_message "Failed to connect to $SSID."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment