In this tutorial, How do I use bash string comparison? In the bash shell use the if statement “==” to check equality and “!=” to check the inequality of the string. String comparison examples. Bash script the essential for DevOps Roles.
In bash, you can compare strings using various operators. Here are some common string comparison operators in bash:
- = : Checks if two strings are equal
- != : Checks if two strings are not equal
- -z : Checks if a string is empty (has zero length)
- -n : Checks if a string is not empty
- < : Checks if one string is less than another string (in lexicographical order)
- > : Checks if one string is greater than another string (in lexicographical order)
Bash string comparison use “==” operator
#!/bin/bash STRA=huu STRB="www.devopsroles.com" if [[ "$STRA" == "$STRB" ]]; then echo "$STRA equal $STRB" else echo "$STRA not equal $STRB" fi
The screen output terminal:
Bash script string compare use “!=” operator
#!/bin/bash STRA=huu STRB="www.devopsroles.com" if [[ "$STRA" != "$STRB" ]]; then echo "$STRA not equal $STRB" else echo "$STRA equal $STRB" fi
The screen output terminal:
Bash script string compare use wildcards
#!/bin/bash STRA=huu STRB="www.devopsroles.com" if [[ "$STRA" == *$STRB* ]]; then echo "$STRA equal $STRB" else echo "$STRA not equal $STRB" fi
The screen output terminal:
Examples of string comparison in bash
Conclusion
Through the article, you can use Bash string comparison as above. I hope will this your helpful. For more details refer to the Bash script.