Skip to content

Instantly share code, notes, and snippets.

@dnmfarrell
Created December 1, 2023 20:32
Show Gist options
  • Save dnmfarrell/61800ab3fb43898264782e4489949f16 to your computer and use it in GitHub Desktop.
Save dnmfarrell/61800ab3fb43898264782e4489949f16 to your computer and use it in GitHub Desktop.
Bash script to switch to the strongest wifi connection using nmcli
#!/bin/bash
# switches to strongest known wifi connection using nmcli
set -euo pipefail
# returns "name:signal:in-use" in order of signal strength
conn_strength() {
conns=()
while IFS= read -r line; do
conns+=("$line")
done < <(nmcli -t -f name connection show)
while read -r line;do
name="${line%%:*}"
for c in "${conns[@]}";do
[[ "$name" == "$c" ]] && echo "$line"
done
done < <(nmcli -t -f ssid,signal,in-use dev wifi list)
true
}
cur_name=
cur_strn=
max_name=
max_strn=
while read -r line;do
name="${line%%:*}"
strn="${line%:*}"
strn="${strn#*:}"
[[ -z "$max_name" ]] && max_name="$name" && max_strn="$strn"
[[ "${line##*:}" == '*' ]] && cur_name="$name" && cur_strn="$strn"
done < <(conn_strength)
dif_strn=$(( max_strn-cur_strn ))
req_gain=20 # don't flap between similar-strength connections
if [[ "$max_name" != "$cur_name" ]] && [[ "$dif_strn" -ge "$req_gain" ]];then
nmcli device wifi connect "$max_name"
fi
true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment