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!
Asked
Active
Viewed 3.4k times
6
-
Are you using a bash script? You can grab the contents of test.txt by doing `cat test.txt` and then compare with your string. – user3885927 Aug 31 '16 at 21:55
-
Please [edit] your question to show [what you have tried so far](http://whathaveyoutried.com). You should include a [mcve] of the code that you are having problems with, then we can try to help with the specific problem. You should also read [ask]. – Toby Speight Aug 31 '16 at 22:12
4 Answers
19
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
![](../../users/profiles/1126841.webp)
chepner
- 389,128
- 51
- 403
- 529
-
1
-
-
1I had to do `if [[ "$(< test.txt)" != "$str" ]]; then` to get the second option to work properly for multiline files. Note the quotes. – Andreas Løve Selvik Feb 26 '20 at 22:30
10
Something like this should work:
s="ABCD"
if [ "$s" == "$(cat test.txt)" ] ;then
:
else
echo "They don't match"
fi
![](../../users/profiles/2561714.webp)
NickD
- 4,598
- 1
- 17
- 33
7
str="ABCD"
content=$(cat test.txt)
if [ "$str" == "$content" ];then
# send your email
fi
![](../../users/profiles/6715114.webp)
Scott Wang
- 410
- 1
- 6
- 9
-
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 – Tomas Jan 13 '21 at 19:42
0
if [ "$(cat test.tx)" == ABCD ]; then
# send your email
else
echo "Not matched"
fi
![](../../users/profiles/9449478.webp)
sachin_ur
- 1,426
- 12
- 23