How To Compare String In Bash Linux?

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/compare-string-bash-linux/
PINTEREST
PINTEREST
INSTAGRAM

as We generally use bash in order to execute commands. But as bash is a programming environment we have other programming related features. We can compare strings where these strings are output or error of some commands. In this tutorial we will look different use cases for string comparison in Bash Linux.

Compare with Equality

The most used examples for string comparison is comparing equality. We can compare two strings character by character for equality and then return some value or string according to the result. In this example we will check two string variables $s1 $s2 and return result as string like  EQUAL or NOTEQUAL. We will use == for string equality check. -eq will not work because it is only used with numbers or integers.

Compare with Equality

Compare with Equality

Compare For Not Equal

We can use not logic for inequality this is useful like password check. We will check stored password and provided password.We can will use !=as inequality operator.

Compare For Not Equal

Compare For Not Equal

As we can see provided password is different from secret and we print Wrong Password to the screen.

 

Compare Case-Insenstive

While comparing strings case sensitivity is important factor. The default behavior is comparing strings in case sensitive but in some cases we may need to compare them case-insensitive. We can use bash provided nocasematch feature. This feature will disable case sensitivity for bash completely.

LEARN MORE  Linux History Command Tutorial with Examples

Compare Case-Insenstive

Compare Case-Insenstive

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/compare-string-bash-linux/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)