Run backup script only if a specific network connection is activated

I use NetworkManager to handle network connections on my laptop.

Once a day some backup scripts are started automatically. They need a lot of bandwidth and I don’t want them run while I use a low bandwidth mobile connection or when I am not at home.

To get the status of my connection named “Home (LAN)” I use the nmcli tool:

nmcli -t -f 'GENERAL.STATE' connection show "Home (LAN)"

If the connection is not in use the tool returns nothing and if it is in use it returns “GENERAL.STATE:activated”.

Now I can insert the following line into my backup scripts somewhere before it starts the backup stuff. If my home connection is online the script is continued and if not the script exits with a text message.

STATE=$(nmcli -t -f GENERAL.STATE connection show "Home (LAN)"); if [ -z $STATE ]; then echo "Not starting the backup because we are not connected to \"Home (LAN)\"."; exit 15; fi

Thats it 🙂