Lengthy string comparison

Hi Team,

Here's the scenario.

Code:

x="APT_BUFFER_DISK_WRITE_INCREMENT|3\Number\1048576\2\Project\Control buffer flushing\When internal memory buffer fills up, controls how much data gets flushed to disk."
y="${x}"

If I try exec the following.

if [[ ${x} == ${y} ]] then
> echo "same"
> else
> echo "diff"
> fi
diff

The value of both x and y are same. But still the if statement throws "diff"

Can anyone help us to fix this issue?

Hi kmanivan82...

Assuming bash or similar.

Try: if [[ "${x}" == "${y}" ]] instead.

To explain a little more, the string you want to compare has spaces in it. The syntax of the if test is does this item have a relationship with another item. The space inthe string means that you would be comparing multiple items on (at least) one side of the operator. Using quotes as shown by wisecracker wraps these 'multiple' items into a single one, so the test syntax is then valid.

It is always good practice to quote for this reason. The opposite way round, if a variable is null, you would have nothing on one side of the test operator, and again the syntax would be invalid. Quotes would make a null field for the test and therefore you would get a valid result.

I hope that this explanation is useful. It's effectively the same reason that you coded y="${x}" in your original post. Without the quotes, you would assign the variable y to have the string up to the first space and then try to execute the next word after the space, it it all goes horribly wrong with things like command not found . Imagine if your string x was set and used like this:-

x="Hidden_bug_string rm -fv /boot/* ; reboot"
y=$x

Results might be a little undesirable.

Kind regards,
Robin

The problem is that within [[ ]] the == does a glob match rather than a string comparison.
In your case a \X in the glob pattern becomes a X and that differs.
Therefore, the right side of the == must be in quotes in order to escape the glob match and become a string match.

if [[ $x == "$y" ]]

is sufficient; of course

if [[ "$x" == "$y" ]]

looks better.
Compare with

if [ "$x" = "$y" ]

where within [ ] the = always does a string comparison, but, because [ is a command, the shell first does a glob match against the current directory on both sides, and then compares the resulting strings. So both sides of the = must be in quotes.

@rbatte1, I disagree a bit with your post:
1.
spaces in a string are only a problem when word splitting applies, like in command arguments, and [ is a command but [[ is NOT. Word splitting in [[ ]] takes place only in literal strings such as

[[ "two words" == "two words" ]]

but not in

a="two words"
b=$a
[[ $a == $b ]]
x="Hidden_bug_string rm -fv /boot/* ; reboot"
y=$x

is perfectly okay, because it is an assignment, where the shell only expands literal strings.

1 Like