Bash Strings Equal

Bash Strings Equal – In this tutorial, we shall learn how to check if two strings are equal in bash scripting.

To check if two strings are equal in bash scripting, use bash if statement and double equal to ==  operator.

To check if two strings are not equal in bash scripting, use bash if statement and not equal to !=  operator.

Example 1 – Strings Equal Scenario

In this example program, we will check if two strings are equal using IF statement and Equal-to operator.

Bash Script File

</>
Copy
#!/bin/bash

str1="Learn Bash"
str2="Learn Bash"

if [ "$str1" == "$str2" ]; then
	echo "Both Strings are Equal."
else
	echo "Both Strings are not Equal."
fi

Output

~/workspace/bash$ ./bash-strings-equal-example 
Both Strings are Equal.

Example 2 – Strings Not Equal Scenario

In this example program, we will check if two strings are not equal using IF statement and Not-Equal-to operator.

Bash Script File

#!/bin/bash

str1="Learn Bash"
str2="Learn Bash with tutorialkart"

if [ "$str1" != "$str2" ]; then
	echo "Both Strings are not Equal."
else
	echo "Both Strings are Equal."
fi

Output

~/workspace/bash$ ./bash-strings-equal-example-1 
Both Strings are not Equal.

Conclusion

In this Bash TutorialBash Strings Equal, we have learnt to check if two strings are equal or not with the help of double equal to and not equal to operators.