2

I have written the following line as a bash:

nmcli nm status id "My VPN id"> /home/Desktop/1.txt

So I want to check the id status and save it in the 1.txt file.

Now I want to search in 1.txt file and if it finds the word "connected" then do nothing and if it does not find it run the following line:

nmcli con up id "My VPN id"

How can I write the search part?

Edit: I made a bash script on a document on Desktop (with a name "s.sh" as follows:

#!/bin/sh

nmcli nm status id 1> /home/Desktop/1.txt
grep -q connected /home/Desktop/1.txt || nmcli con up id 1

and edit the crontab as follows: enter image description here

Saved the file. But the cron does not work!

P.A.M
  • 123
  • 7

1 Answers1

3

To execute a command only if connected is not in 1.txt:

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.

The -q option to grep tells grep to be quiet. When used with -q, instead of printing output, grep will simply set a return code.

Crontab

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.

Without crontab

while sleep 60m
do
    grep -q connected /home/Desktop/1.txt || nmcli con up id "My VPN id"
done
John1024
  • 109,961
  • 14
  • 137
  • 171
  • thanks a lot. that helped. and if I want to make this script run every 60 min. What should I do?! – P.A.M Sep 25 '16 at 19:39
  • 1
    To run it every hour, I would put it in `crontab`. – John1024 Sep 25 '16 at 19:40
  • and how to do it, please? :D or where can i find information about using crontab to schedule? – P.A.M Sep 25 '16 at 19:42
  • 1
    @P.A.M See updated answer for some `crontab` info. `crontab` is very useful. I recommend reading [a tutorial](https://www.google.com/search?q=how+to+use+crontab) on it. – John1024 Sep 25 '16 at 19:53
  • thanks so much for your help. – P.A.M Sep 25 '16 at 19:54
  • my crontab doesnt work :( – P.A.M Sep 25 '16 at 21:44
  • 1
    @P.A.M _"doesnt work"_ That is obviously not enough information for anyone to be able to diagnose a problem and offer help. As an alternative, I updated the answer with a simple bash script which will run your program every 60 minutes. – John1024 Sep 25 '16 at 21:54