How can shell determine if two variables are equal?

In a shell, the “==” operator can be used to determine if two variables are equal. Here is an example:

#!/bin/bash

var1="hello"
var2="world"

if [ "$var1" == "$var2" ]; then
  echo "变量相等"
else
  echo "变量不相等"
fi

Be cautious when using the == operator, as it’s crucial to enclose variables in double quotes on both sides to prevent errors if the variable contains spaces or special characters. Additionally, the == operator is only meant for comparing strings; for comparing numbers, use -eq, -ne, -gt, and so on.

bannerAds