P.A.M P.A.M - 1 year ago 58
Linux Question

search for a word in file in bash and execute something if the word is present

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

Now I want to search in
file and if it finds the word
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?

Answer Source

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
    nmcli con up id "My VPN id"

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.


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download