Bash String Comparisons
Use the double equals ( == ) operator to compare strings inside square brackets []. Using this option you simply test if two given strings are equal or not inside bash shell scripts.
Example Syntax:
if [ "$str1" == "$str2" ] # True if equal
if [ "$str1" != "$str2" ] # True if not equal
Example:
For example, to compare whether two strings are equal or not.
if [ "hello" == "hello" ] ## True
if [ "hello" == "hello1" ] ## False
if [ "hello" != "hello" ] ## False
if [ "hello" != "hello1" ] ## True
Take input of two strings in a script and compare if both are the same or not, using if statement.
| #!/bin/bash read -p "Enter first string: " str1 read -p "Enter second string: " str2 if [ "$str1" == "$str2" ] then echo "Both strings are same" else echo "Both strings are different" fi |
0 Comments
CAN FEEDBACK
Emoji