cli linux wifi shell functions tab complete tips

When to Make Shell Wrappers

Often, some command-line tools might have hard-to-remember sequences for certain kinds of actions. In these cases, it is completely reasonable to make shell functions to wrap those tools.

Example with nmcli

A good quick example of this is nmcli, the command-line tool for controlling NetworkManager on Linux. The multi-part command for connecting to a wifi network is pretty different than reconnecting to a network.

Listing available networks

nmcli dev wifi list

Connecting for the first time

sudo nmcli --ask dev wifi connect <some-ssid>

Re-connecting in the future

nmcli con up <some-ssid>

Wrapper shell functions for nmcli

Here are some tab-completable shell functions defined in my base/commands.sh file for nmcli that should work fine in bash or zsh:

if type nmcli &>/dev/null; then
    nmcli-list-networks() {
        nmcli dev wifi list | cut -c 28-
    }

    nmcli-status() {
        nmcli dev status
    }

    nmcli-connect-to() {
        ssid="$1"
        [[ -z "$ssid" ]] && echo "No SSID specified" && return 1
        sudo nmcli --ask dev wifi connect "$ssid"
    }

    nmcli-reconnect-to() {
        ssid="$1"
        [[ -z "$ssid" ]] && echo "No SSID specified" && return 1
        nmcli con up "$ssid"
    }
fi

When I want to “do an nmcli thing” I just need to type nmcli-<tab> to show me the available names (nmcli-connect-to, nmcli-list-networks, nmcli-reconnect-to, and nmcli-status). That’s the beauty of tab-completion (especially if you name things well)!

Avatar photo Open Source Enthusiast connecting learners, builders, educators, and teams.