Shell Script compare file content with a string

38,522

Solution 1

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

Solution 2

Something like this should work:

s="ABCD"
if [ "$s" == "$(cat test.txt)" ] ;then
    :
else
    echo "They don't match"
fi

Solution 3

str="ABCD"
content=$(cat test.txt)
if [ "$str" == "$content" ];then
    # send your email
fi

Solution 4

if [ "$(cat test.tx)" == ABCD ]; then
           # send your email
else
    echo "Not matched"
fi
Share:
38,522
Admin
Author by

Admin

Updated on December 19, 2020

Comments

  • Admin
    Admin over 3 years

    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!

  • neverMind9
    neverMind9 over 5 years
    This is the better solution.
  • Andrei LED
    Andrei LED over 4 years
    Second option also allows to assert multiline text file content
  • Andreas Løve Selvik
    Andreas Løve Selvik over 4 years
    I had to do if [[ "$(< test.txt)" != "$str" ]]; then to get the second option to work properly for multiline files. Note the quotes.
  • Tomas Reimers
    Tomas Reimers over 3 years
    I think you may need to add a not to your if statement? The author sounds as if they want to send the email if the contents does not match