Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script compare file content with a string

I have a String "ABCD" and a file test.txt. I want to check if the file has only this content "ABCD". Usually I get the file with "ABCD" only and I want to send email notifications when I get anything else apart from this string so I want to check for this condition. Please help!

like image 366
ashutosh tripathi Avatar asked Aug 31 '16 21:08

ashutosh tripathi


2 Answers

Update: My original answer would unnecessarily read a large file into memory when it couldn't possibly match. Any multi-line file would fail, so you only need to read two lines at most. Instead, read the first line. If it does not match the string, or if a second read succeeds at all, regardless of what it reads, then send the e-mail.

str=ABCD
if { IFS= read -r line1 &&
     [[ $line1 != $str ]] ||
     IFS= read -r $line2
   } < test.txt; then
    # send e-mail
fi 

Just read in the entire file and compare it to the string:

str=ABCD
if [[ $(< test.txt) != "$str" ]]; then
    # send e-mail
fi
like image 179
chepner Avatar answered Oct 20 '22 16:10

chepner


Something like this should work:

s="ABCD"
if [ "$s" == "$(cat test.txt)" ] ;then
    :
else
    echo "They don't match"
fi
like image 26
NickD Avatar answered Oct 20 '22 18:10

NickD