Home > database >  Bash String Comparison sha256sum
Bash String Comparison sha256sum

Time:06-17

I am trying to compare the hash of a copied file with bash but the condition is not working.

└──╼ $bash check-256.sh cal.sh 2cal.sh 

ea8f4b5acdeb26015661ee27c9000af97691a0fd715be94b2b3eda6a3d02c789  cal.sh
ea8f4b5acdeb26015661ee27c9000af97691a0fd715be94b2b3eda6a3d02c789  2cal.sh
#!/bin/bash
First_file=$(sha256sum $1)
Second_file=$(sha256sum $2)
echo "$First_file"
echo "$Second_file"
[ "$First_file" == "$Second_file" ] &&  echo "Pass" || echo "Fail"

CodePudding user response:

The condition fails, because the resulting strings are actually not the same. You need to cut out the hash by using the cut command.

#!/bin/bash
First_file=$(sha256sum $1 | cut -d' ' -f1)
Second_file=$(sha256sum $2 | cut -d' ' -f1)
echo "$First_file"
echo "$Second_file"
[ "$First_file" == "$Second_file" ] &&  echo "Pass" || echo "Fail"
cut -d' ' -f1
  • -d specifies the delimiter. In this case we use a single space
  • -f1 selects the field of the output. Here we want to only have the first field, which is the hash
  • Related