Skip to content

Instantly share code, notes, and snippets.

@jovandeginste
Created May 1, 2020 09:17
Show Gist options
  • Save jovandeginste/dd74b585b088e283252436ccd948cc84 to your computer and use it in GitHub Desktop.
Save jovandeginste/dd74b585b088e283252436ccd948cc84 to your computer and use it in GitHub Desktop.
Simple script to switch to best WiFi signal if current signal falls below threshold (using nmcli)
#!/bin/bash -eu
# We don't need to switch if current signal has at least this this strength:
GOOD_ENOUGH=50
# Signal to switch to, must at least have this strength:
BETTER=60
# We use 'autoconnect' here, to later filter SSID's explicitly not
# configured as 'autoconnect'.
KNOWN_SSIDS=$(nmcli -g name,type,autoconnect connection show)
# To speed up, we don't need the most recent data, so don't rescan
WIFI_SIGNALS=$(nmcli -g ssid,signal,in-use dev wifi list --rescan no)
# The in-use field is '*' if it is in use.
CURRENT_SIGNAL=$(awk -F: '{if ($3 == "*") { print $2}}' <<<"${WIFI_SIGNALS}")
echo "Current signal: '${CURRENT_SIGNAL}'"
if [[ "${CURRENT_SIGNAL}" -ge "${GOOD_ENOUGH}" ]]; then
echo "Current signal is good enough."
exit
fi
while IFS=':' read -r ssid signal in_use; do
echo "Signal for '${ssid}': ${signal}"
if [[ "${signal}" -le "${BETTER}" ]]; then
echo "No better signal found."
exit
fi
# We check if we know this SSID, and if it is set to autoconnect
if grep -q "^${ssid}:.*:yes$" <<<"$KNOWN_SSIDS"; then
echo "Switching to: '${ssid}' (${signal})"
nmcli connection up "${ssid}"
exit
fi
done <<<"$WIFI_SIGNALS"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment