Search code examples
shellubuntugrepmd5sum

Check existing md5sum exist in file - Shell script


I'm using Ubuntu 14.04. I have a list of md5 hashed text that stored in a.txt file. Now i will input a text, i will hash it and check if the result is in my file or not. I'm using grep to do it but the script just work for a static string.

My script file looks like

file="a.txt"
s1="81dc9bdb52d04dc20036dbd8313ed055 -"
echo "s1: "$s1

s2=$(echo -n "1234" | md5sum)
echo "s2: "$s2


if grep -Fx "$s1" "$file"; then
        echo 's1 FOUND'
else
        echo 's1 NOT FOUND'
fi

if grep -Fx "$s2" "$file"; then
        echo 's2 FOUND'
else
        echo 's2 NOT FOUND'
fi

In the a.txt file, i have only 1 line:

81dc9bdb52d04dc20036dbd8313ed055 -

As above script, you can see, i set the value of s1 as a static string and the s2 is result of hashed.

The output that i got:

s1: 81dc9bdb52d04dc20036dbd8313ed055 -
s2: 81dc9bdb52d04dc20036dbd8313ed055 -
81dc9bdb52d04dc20036dbd8313ed055 -
s1 FOUND
s2 NOT FOUND

As i can see on the screen - s1 and s2 have same value. s1 is found in file but not s2. I don't understand what's wrong here and how to fix.


Solution

  • $s1 contains one space. Output of echo -n "1234" | md5sum contains two.


    Replace

    echo "s1: "$s1
    echo "s2: "$s2
    

    by

    echo "s1: $s1"
    echo "s2: $s2"
    

    to see the problem.


    Replace

    s2=$(echo -n "1234" | md5sum)
    

    by

    s2=$(echo -n "1234" | md5sum | sed 's/  / /')
    

    to fix this problem.