Home > Software engineering >  Comparing two string variables in bash
Comparing two string variables in bash

Time:06-09

This block of code keeps echoing "they are equal" Why?

#!/bin/bash

foo="hello"
bar="h"
if [[ "$foo"=="$bar" ]]; then
        echo "they are equal"
else
        echo "they are not equal"
fi

CodePudding user response:

The condition works based on the number of elements within it, and this particular issue is covered by this (paraphrased) part of the man-page:

string: True if the length of string is non-zero.

string1 == string2: True if the strings are equal.

In other words, a comparison needs three elements, meaning you need a space on either side of the ==.

Without that it's simply the one-element variant of the condition, which is true when the string is non-empty, as hello==h most definitely is.

  • Related