bash check if string does not exist in file 1

bash check if string does not exist in file

Just use grep with flags 'F' (fixed string), 'x' (exact match) and 'q'
(quiet output) in order to check if a word string is in a file
if ! grep -Fxq "string" file.txt; then #do some code...#; fi

Here is what the above code is Doing:
1. The ! is a negation operator.
2. The grep command is searching for the string “string” in the file file.txt.
3. The -F flag tells grep to search for a fixed string.
4. The -x flag tells grep to search for an exact match.
5. The -q flag tells grep to be quiet.
6. The if statement is checking the exit status of grep.
7. If the exit status is 0, then the string was found.
8. If the exit status is 1, then the string was not found.
9. If the exit status is 2, then there was an error.

Similar Posts