I have written the following line as a bash:
nmcli nm status id "My VPN id"> /home/Desktop/1.txt
nmcli con up id "My VPN id"
To execute a command only if
connected is not in
grep -q connected /home/Desktop/1.txt || nmcli con up id "My VPN id"
grep string file will return exit code 0 (success) if the regex
string is found in
file. To execute a command only if
grep returns with fail, we use the shell's logical-or:
As an alternative, we can use a full if-then statement:
if ! grep -q connected /home/Desktop/1.txt then nmcli con up id "My VPN id" fi
Again, we only want to run the command if
grep -q connected /home/Desktop/1.txt returns fail. To do that, we use
! to negate the return code. In this way the command will run if
grep returns with a fail code.
-q option to
grep to be quiet. When used with
-q, instead of printing output,
grep will simply set a return code.
To run this command every hour on the hour, run
crontab -e. This will raise an editor. In the editor, add the line:
0 * * * * /bin/grep -q connected /home/Desktop/1.txt || /path/to/nmcli con up id "My VPN id"
Now, save the file and exit the editor.
For more information on the very useful
crontab, see here.