0

When I run the command

nmcli --get-values TYPE connection show --active

I sometimes receive a list of values as follows

vpn
802-3-ethernet
tun
tun

But other times the vpn line is not present. (the order of the lines cannot be assumed)

I'm looking for a one-liner that will accept the output of that nmcli command (presumably via pipe/stdin?) and return an exit code of 1 when vpn is in that list and an exit code of 0 when vpn is not in that list.

What I've Tried

  • Every combination of grep that I can think of. grep -v will absolutely not work because it will always find a line that is not vpn. Other options to grep return data, but do not change the error code (that I can find).
  • Every negation regex I can find or think of. Regexes in the form ^(?!vpn).*$ do not work because there will always be a line that does not say vpn.

Use Case

I am writing a systemd service to update my dynamic DNS. But I don't want to set my dynamic DNS while I'm on a VPN. I want to use systemd built-in abilities (as much as possible) to control it. So I want to use the systemd built-in ExecStartPre= (which fails the unit on exit code 1+) to control whether the service starts.

If you've got a way to run a service (or not) using systemd depending on whether a VPN is connected, I'll accept that in lieu of the above. But naive assumptions like "tun0 active=VPN" are false for me. I have various tun connections active at any one time, for various reasons. So triggering on sys-subsystem-net-devices-tun0.device does not work.

What Doesn't Work

Most of the Google and SO results I find are for line-specific negation and do not address my use case where there will be multiple lines. Or they return the values and do not set the error code. I need error codes set.

Cliff
  • 109
  • 6

1 Answers1

1

Instead of just checking for existence of vpn in the output, count the number of occurences, then evaluate a conditional expression checking on the number of lines:

nmcli --get-values TYPE connection show --active | [ $(grep -c ^vpn) -eq 0 ]
Jürgen Hötzel
  • 16,398
  • 3
  • 38
  • 55
  • Oh, wow. I've never even **heard of** piping into a conditional expression, much less into command substitution like that! Thank you!!! – Cliff May 06 '20 at 04:27