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.


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.


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 $?

Example 2:

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

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

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";


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.

if grep -q $PATTERN $FILE;
     echo "Here are the Strings with the Pattern '$PATTERN':"
     echo -e "$(grep $PATTERN $FILE)\n"
     echo "Error: The Pattern '$PATTERN' was NOT Found in '$FILE'"
     echo "Exiting..."
     exit 0

Save the script, give the execute permissions and execute:

chmod +x
./ root /etc/passwd
Here are the Strings with the Pattern 'root':
./ John /etc/passwd
Error: The Pattern 'John' was NOT Found in '/etc/passwd'

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

  1. NIce tutorial! Thanks for sharing.

Leave a Reply