Bash string comparison

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 string comparison

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 string comparison

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:

Bash string comparison

Examples of string comparison in bash

bash script strings

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.

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.