HowTo: Check If a String Exists

Sometimes, we need to check if the pattern presents in a file and take some actions depending on the result.

It can be done with the help of ‘exit status codes’. Each Linux command returns a status when it terminates normally or abnormally

You can use command exit status in the shell script to display an error message or perform some sort of action.

Syntax

grep -q [PATTERN] [FILE] && echo $?
  • The exit status is 0 (true) if the pattern was found;
  • The exit status is 1 (false) if the pattern was not found.

Examples

Here are some examples of checking if the string, that contains some pattern, presents it the file.

Example 1:

The following example shows that ‘SOME_PATTERN’ presents in ‘SOME_FILE’.

grep -q 'SOME_PATTERN' 'SOME_FILE' && echo $?
0

Example 2:

The next example shows that ‘ANOTHER_ONE_PATTERN’ doesn’t present in ‘SOME_FILE’.

grep -q 'ANOTHER_ONE_PATTERN' 'SOME_FILE' && echo $?
1

Example 3:

Checking if the string presents, and printing the error message if it doesn’t.

grep -q 'PATTERN' 'FILE' || echo "Error: The Pattern Does Not Exist";

Output:

Error: The Pattern Does Not Exist

BASH Script

Let’s check if the pattern exist in the file. If it exists, we will print all the strings that contain the pattern. If it doesn’t exist we will print the error message and stop the script.

#!/bin/bash
PATTERN=$1
FILE=$2
if grep -q $PATTERN $FILE;
 then
     echo "Here are the Strings with the Pattern '$PATTERN':"
     echo -e "$(grep $PATTERN $FILE)\n"
 else
     echo "Error: The Pattern '$PATTERN' was NOT Found in '$FILE'"
     echo "Exiting..."
     exit 0
fi

Save the script, give the execute permissions and execute:

chmod +x script.sh
./script.sh root /etc/passwd
Here are the Strings with the Pattern 'root':
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
./script.sh John /etc/passwd
Error: The Pattern 'John' was NOT Found in '/etc/passwd'
Exiting...

One Reply to “HowTo: Check If a String Exists”

  1. NIce tutorial! Thanks for sharing.

Leave a Reply