Bash script - Check if a file contains a specific line
From the grep's man:
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected. Also see the -s or --no-messages option.
-F, --fixed-strings
Interpret PATTERNS as fixed strings, not regular expressions.
-x, --line-regexp
Select only those matches that exactly match the whole line. For a regular expression pattern, this is like parenthesizing the pattern and then surrounding it with ^ and $.
# Inline
grep -q -F "$STRING" "$FILE" && echo 'Found' || echo 'Not Found'
grep -q -F "$STRING" "$FILE" || echo 'Not Found'
# Multiline
if grep -q -F "$STRING" "$FILE"; then
echo 'Found'
else
echo 'Not Found'
fi
if ! grep -q -F "$STRING" "$FILE"; then
echo 'Not Found'
fi
If you need to check the whole line use -x
flag:
grep -q -x -F "$STRING" "$FILE" && echo 'Found' || echo 'Not Found'
if $FILE
contains the file name and $STRING
contains the string to be searched,
then you can display if the file matches using the following command:
if [ ! -z $(grep "$STRING" "$FILE") ]; then echo "FOUND"; fi
Poll the file's modification time and grep for the string when it changes:
while :; do
a=$(stat -c%Y "$FILE") # GNU stat
[ "$b" != "$a" ] && b="$a" && \
grep -q "$STRING" "$FILE" && echo FOUND
sleep 1
done
Note: BSD users should use stat -f%m