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.
The following example shows that ‘SOME_PATTERN’ presents in ‘SOME_FILE’.
grep -q 'SOME_PATTERN' 'SOME_FILE' && echo $? 0
The next example shows that ‘ANOTHER_ONE_PATTERN’ doesn’t present in ‘SOME_FILE’.
grep -q 'ANOTHER_ONE_PATTERN' 'SOME_FILE' && echo $? 1
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
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...