In addition to the error of using cmp
for comparing strings where it only compares files, you have the problems that you are actually calculating the length of the error message from cmp
, and extracting the file name, not the character count, from the output from wc
. The entire computation would be a lot more elegant without a temporary file; if you do use a temporary file, you should clean it out after using it.
If you really wanted to see the amount of difference between two strings, maybe pass them to wdiff
instead.
Here is a refactored version:
#!/bin/bash
# Note absence of boilerplate comment
read -p "Enter first word: " test1 # Note use of read -p
read -p "Enter second word: " test2
# Note use of wdiff
# Note proper quoting of strings! This is important
if report=$(wdiff -s123 <(echo "$test1") <(echo "$test2")); then
echo "Strings are equal"
else
echo "Strings differ"
echo "$report"
fi
As an aside, a basic idiom with wc
is to redirect input into it; then, it doesn't print a file name, so you don't have to postprocess it. And lo, this also removes the need for a temporary file.
total=$(cmp one two | wc -c)