1

Here comes my script, i know i'm doing something wrong so please help me!

#!/bin/bash
# Description of the script

echo "Enter first word "
read test1
echo "Enter second word "
read test2

cmp $test1 $test2 > error

total=`wc -c error | cut -f 7 -d " "`
echo $total

if [ $total -eq 0 ]
then
        echo "Both words contents are same"else
        echo "Both words contents are not same"
fi

3 Answers 3

4

Unless you have to use cmp, you can use [ ] for comparison:

if [ "$test1" = "$test2" ]
then
        echo "Both words contents are same"
else
        echo "Both words contents are not same"
fi

cmp compares files. If, say, you entered foo for test1 and bar for test2, then it will compare two files named foo and bar, which is probably not what you intended.

Aside from that, this line:

echo "Both words contents are same"else

is the same as:

echo "Both words contents are sameelse"

You should either put else on a different line, or put a ; before it:

echo "Both words contents are same"
else
# or
echo "Both words contents are same"; else
1

Why use cmp? You are already using a bash conditional later in your script, so you could swap out the cmp. Example conditional:

if [ "$test1" != "$test2" ]; then
     # not equal
else
     # equal
fi

Other comparison operators in bash.

1

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)
1
  • If you found this answer helpful, please consider upvoting or perhaps even accepting it. Thanks!
    – tripleee
    Nov 30, 2015 at 8:36

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .