How to delete a connection by type with nmcli?

13.3k views Asked by At

I want to have a bash script that can delete all my network manager connections of type gsm with nmcli.

What is the best approach for this?

3

There are 3 answers

1
Sam Calvert On

This is actually a trickier question than it seems on the surface, because NetworkManager allows for connection names with spaces in them. This makes programmatic parsing of the output of nmcli connection show for connection names a bit awkward. I think the best option for scripting would be to rely on the UUID, since it seems to consistently be a 36 character group of hexidecimal characters and dashes. This means we can pull it consistently with a regular expression. So for example you could get a list of the UUIDs for gsm connections with the following:

$ nmcli connection show | grep gsm | grep -E -o '[0-9a-f\-]{36}'
cc823da6-d4e1-4757-a37a-aaaaaaaaa
etc

So you could grab the UUIDs and then delete based on the UUID:

GSM_UUIDS=$(nmcli connection show | grep gsm | grep -E -o '[0-9a-f\-]{36}')
while IFS= read -r UUID; do echo nmcli connection delete $UUID; done <<< "$GSM_UUIDS"

Run with the echo to make sure you're getting the result you expect, then you can remove it and you should be in business. I ran locally with some dummy GSM connections and it seemed to work they way you would want it to:

GSM_UUIDS=$(nmcli connection show | grep gsm | grep -E -o '[0-9a-f\-]{36}')
while IFS= read -r UUID; do nmcli connection delete $UUID; done <<< "$GSM_UUIDS" 
Connection 'gsm' (cd311376-d7ab-4891-ba73-e4e8a3fc6614) successfully deleted.
Connection 'gsm-1' (54171181-5c37-4224-baf5-9eb36458f773) successfully deleted.
2
Yaroslav752 On
nmcli con del $(nmcli -t -f UUID,TYPE con | awk -F":" '{if ($2 == "gsm") print $1}')
0
Kevin Keane On

Elaborating on and de-cryptifying the answer from @Yaroslav752 :

ethernet_uuids=$(nmcli -t -f UUID,TYPE connection show | awk -F":" '{if ($2 == "gsm") print $1}')
nmcli connection delete $ethernet_uuids

The command

nmcli -t -f UUID,TYPE connection show

is a standard connection show, but with format specifiers.

-f UUID,TYPE means: only display the fields UUID and TYPE, and in that order. This avoids edge cases, such as an Ethernet connection with the name "This is not a gsm connection"

-t changes the output format to omit the header, and use a colon instead of a space as separator between the UUID and the TYPE.

The awk expression skips anything where the second field is not the word "gsm". If the second field is gsm, it prints the first field (i.e., the UUID).

My version stores these uuids in a variable, and then passes that variable to the nmcli connection delete command. That's simply for readability; I'm not a big fan of one-liners.