A Simple bash script to modify macOS DNS by detecting SSID

I believe most of us have different DNS settings for different networks. For example, in my case, I use Google’s public DNS 8.8.8.8 and Cloudflare’s 1.1.1.1 at home, but at work, I have to clearthe DNS reacord and let my Mac use the default DNS provided by the company.

It’s a bit annoying to change the DNS settings manually every time I switch networks. So I wrote a simple bash script to automatically change the DNS settings based on the SSID of the network I’m connected to.

Here is the script:

#!/bin/bash
# clear or set dns
function set_or_clear_dns() {
    local current_ssid=$(networksetup -getairportnetwork en0 | cut -d ':' -f 2 | xargs)

    if [[ "$current_ssid" == "YOUR_COMPANY_WIFI_SSID" ]]; then 
        # Clear DNS to Automatic (Empty)
        sudo networksetup -setdnsservers Wi-Fi empty
    else
        # Set DNS to 1.1.1.1 and 8.8.8.8
        sudo networksetup -setdnsservers Wi-Fi 1.1.1.1 8.8.8.8
    fi
}
set_or_clear_dns

You can replace YOUR_COMPANY_WIFI_SSID with your company’s Wi-Fi SSID. Ofcause, you can add more SSID conditions and DNS settings as needed. And in the code I just simply clear the DNS settings to automatic when connected to the company’s Wi-Fi, you can also set it to other DNS servers, by replacing empty with the DNS servers you want to use.